[英]How do you add/remove hidden in <p hidden> with JavaScript
How do you add and remove 'hidden'
from <p hidden>My Text</p>
?如何在
<p hidden>My Text</p>
中添加和删除'hidden'
?
I tried removing the attribute and setting it to false but neither of them worked.我尝试删除该属性并将其设置为 false 但它们都不起作用。
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
It looks fine here.这里看起来不错。 Try with this code if you wish.
如果您愿意,请尝试使用此代码。
index.html索引.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您可以在 codePen https://codepen.io/anon/pen/qozVaq 中看到
Could you set an ID on the <p>
tag and interact with it that way?你能在
<p>
标签上设置一个 ID 并以这种方式与之交互吗?
<p id="whatever" hidden>My Text</p>
And:并且:
let p = document.getElementById('whatever');
p.removeAttribute("hidden");
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/这是工作版本: https : //jsfiddle.net/j0467m8m/15/
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>
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.
删除显示样式,你应该很高兴。
Instead of using addAttribute
and removeAttribute
use:而不是使用
addAttribute
和removeAttribute
使用:
myText.hidden = false
// or
myText.hidden = true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.