3

I am making a plugin for form validation as practice, but for some reason after I create a h2 element and try to set it's attribute, it is not working. Here is the code

    var testing = function(regex, value, error_msg, error_msg_field_id){
        var pattern = new RegExp(regex);
        if (!pattern.test(value)){
            var ele = document.createElement("H2");
            var node = document.createTextNode(error_msg);
            ele.setAttribute('style', 'color:white');
            alert("hi");
            jQuery(error_msg_field_id).append(node);
        }
    }

the text appears with no problem, but it is not in white color. This make no sense at all to me

4

1 回答 1

5

您正确使用了setAttribute,但是您在 h2 元素上设置了该属性,该属性实际上从未插入到您的 DOM 中。

您可以将代码的相关部分更改并简化为:

var ele = document.createElement("H2");
ele.textContent = error_msg;
ele.setAttribute('style', 'color:white');
jQuery(error_msg_field_id).append(ele);

这里也没有必要使用jQuery 。你可以简单地使用

document.querySelector("#" + error_msg_field_id).appendChild(ele);

这同样简单。

于 2013-09-23T23:24:56.047 回答