Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 818
user308553 Avatar asked Aug 08 '26 04:08

user308553


1 Answers

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.

like image 138
Thorben Croisé Avatar answered Aug 11 '26 13:08

Thorben Croisé



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!