Search code examples
javascripthtmlcssdomstyles

Variable set to global does not style element


I have the following code:

let fireball; //global variable

fireball = document.createElement("img") //variable on local
fireballArray.push(someFunction(fireball, {
 src: "img.png", width: "38" }))

fireball.style.display = "none" //global variable

My objective is that fireball = document.createElement("img") can be styled (in this case, hidden)

However, document.createElement("img") does not hide. Any help? Thanks

Warning: fireball = document.createElement("img") this variable must remain on local scope and style.display: none must be on another scope (as seen on code)


Solution

  • When you create your img:

    function myFunction() {
      var fireball = document.createElement("img");
      fireball.setAttribute("src", "img_pulpit.jpg");
      fireball.setAttribute("width", "304");
      fireball.setAttribute("height", "228");
      fireball.setAttribute("alt", "The Pulpit Rock");
      fireball.setAttribute("id", "UniqId"); // It is important to set an uniq ID
      document.body.appendChild(fireball);
    }
    

    Then to apply the set, get the Element by Id getElementById:

    function myFunction2() {
      var fireball = document.getElementById("UniqId");
      fireball.setAttribute("style", "display:none; border:3px solid red;");
      document.body.appendChild(fireball);
    }
    

    You can try with w3C demo : https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_img_create