Reputation: 1059
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
Upvotes: 28
Views: 84861
Reputation: 99
call switchHiddenAttribute
function for selected element
const switchHiddenAttribute = (element) => {
element.hidden = !element.hidden;
}
Upvotes: 0
Reputation: 11
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", "");
});
Upvotes: 1
Reputation: 13761
Instead of using addAttribute
and removeAttribute
use:
myText.hidden = false
// or
myText.hidden = true
Upvotes: 3
Reputation: 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.
Upvotes: -1
Reputation: 383
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");
Upvotes: 22
Reputation: 15698
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>
Upvotes: 0
Reputation: 85
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/
Upvotes: 1
Reputation: 2305
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
Upvotes: 19