Search code examples
javascripthtmlattributeshidden

How do you add/remove hidden in <p hidden> with JavaScript


How do you add and remove 'hidden' from <p hidden>My Text</p>?

I tried removing the attribute and setting it to false but neither of them worked.

  let p = document.getElementsByTagName('p');
  let myText;
    
  for (i = 0; i < p.length; i++) {
    if (p[i].innerHTML == "My Text") {
      myText = p[i];
      break;
    }
  }

  myText.removeAttribute("hidden"); // no effect
  myText.setAttribute("hidden", false); // no effect

Solution

  • It looks fine here. Try with this code if you wish.

    index.html

    <html>
    <head>
    
    </head>
    <body>
          <p hidden>My Text</p>
    </body>
    </html>
    

    script

    let p = document.getElementsByTagName('p');
    let myText;
    
    for (i = 0; i < p.length; i++) {
      if (p[i].innerHTML == "My Text") {
        // console.log(myText, p[0].innerHTML);
        myText = p[i];
        break;
      }
    }
    
    myText.removeAttribute("hidden"); 
    

    You can see in codePen https://codepen.io/anon/pen/qozVaq