Javascript: how do you add and remove hidden in <p hidden>

CptHowdyRD0 picture CptHowdyRD0 · Apr 14, 2018 · Viewed 18.7k times · Source

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

Answer

Wesley Gon&#231;alves picture Wesley Gonçalves · Apr 14, 2018

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