setAttribute not working
14,668
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.
Related videos on Youtube
Author by
user308553
Updated on June 09, 2022Comments
-
user308553 almost 2 years
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
-
Ohgodwhy over 10 years
ele.style.color = white;
? -
Roy Miloh over 10 yearsBTW, just a recommendation: use
console.log
instead ofalert
(unless you check your code in IE). -
Roy Miloh over 10 years@user308553 Where did you attach
ele
? you crated the element but didn't attach it to the document. -
Robbie Wxyz over 10 yearsWhy didn't you use
innerHTML
instead ofcreateTextNode
andjQuery.append
? It's faster. -
Thorben Croisé over 10 years@SuperScript, in general, innerHtml is slower(e.g here) than creating and appending elements. And when you simply want to change text,
textContent
is an excellent alternative as you also remove any unwanted insertion of HTML.
-
-
user308553 over 10 yearsHi, is there a advantage in using that instead of jQuery?
-
Thorben Croisé over 10 years1. You don't need jQuery ;) That means you could get around including a library of almost 100k. 2. Using native javascript is almost certainly faster than going through jQuery. 3. You can feel good, because you used native javascript for something that others turn to libraries.
-
Thorben Croisé over 10 yearsThe only time you are in trouble is when using IE7 or below, as these don't know querySelector
-
user308553 over 10 yearsThanks!! this is why I love this site so much. So many great teachers