user308553
user308553

Reputation: 1250

setAttribute not working

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

Upvotes: 3

Views: 24884

Answers (1)

Thorben Croisé
Thorben Croisé

Reputation: 12870

You are using setAttribute correctly, but you are setting the property on your h2-element, which is never actually inserted in your DOM.

You can change and simplify the relevant section of your code to:

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

The usage of jQuery here is also not necessary. You can simply use

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

which is equally simple.

Upvotes: 6

Related Questions