'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 1:[1]

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

Solution 2:[2]

Could you set an ID on the <p> tag and interact with it that way?

<p id="whatever" hidden>My Text</p>

And:

let p = document.getElementById('whatever');
p.removeAttribute("hidden");

Solution 3:[3]

Removing comparison text works fine for me:

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

myText.removeAttribute("hidden");

Here is the working version: https://jsfiddle.net/j0467m8m/15/

Solution 4:[4]

function show(){
x = document.getElementsByTagName('p');
if(x[0].style.visibility === "hidden"){
   x[0].style.visibility = "visible"   
 }else{
   x[0].style.visibility = "hidden"  
}}
<p >this is hidden</p>
<button onClick='show()'>show</button>

Solution 5:[5]

Instead of using addAttribute and removeAttribute use:

myText.hidden = false
// or
myText.hidden = true

Solution 6:[6]

You must have probably given your image a display of block, this can cause the error you have now. Remove display styling, and you should be good to go.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wesley Gonçalves
Solution 2 Penny Liu
Solution 3 iriteshp
Solution 4
Solution 5 Chris Hayes
Solution 6 ABD