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.

Share:
14,668

Related videos on Youtube

user308553
Author by

user308553

Updated on June 09, 2022

Comments

  • user308553
    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
      Ohgodwhy over 10 years
      ele.style.color = white;?
    • Roy Miloh
      Roy Miloh over 10 years
      BTW, just a recommendation: use console.log instead of alert (unless you check your code in IE).
    • Roy Miloh
      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
      Robbie Wxyz over 10 years
      Why didn't you use innerHTML instead of createTextNode and jQuery.append? It's faster.
    • Thorben Croisé
      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
    user308553 over 10 years
    Hi, is there a advantage in using that instead of jQuery?
  • Thorben Croisé
    Thorben Croisé over 10 years
    1. 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é
    Thorben Croisé over 10 years
    The only time you are in trouble is when using IE7 or below, as these don't know querySelector
  • user308553
    user308553 over 10 years
    Thanks!! this is why I love this site so much. So many great teachers

Related