26

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
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Skywarp
  • 989
  • 3
  • 15
  • 32

7 Answers7

19

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

Wesley Gonçalves
  • 1,985
  • 2
  • 19
  • 22
18

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");
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
John Luscombe
  • 343
  • 2
  • 9
2

Instead of using addAttribute and removeAttribute use:

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

Chris Hayes
  • 11,505
  • 6
  • 33
  • 41
1

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/

iriteshp
  • 75
  • 7
0

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>
DCR
  • 14,737
  • 12
  • 52
  • 115
0

I've got something similar, using js to set or remove hidden from a div, it works for fullscreen or 1200px, but didn't work for 690px:

let sidebar = document.querySelector(".dropdown-btn");
let dropdownSidebar = document.querySelector(".three");

dropdownSidebar.addEventListener("click", function(){
   sidebar.hasAttribute("hidden") ? sidebar.removeAttribute("hidden") : sidebar.setAttribute("hidden", "");
});
Michael M.
  • 10,486
  • 9
  • 18
  • 34
-1

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.

ABD
  • 1
  • 1