I want to check if the value inside my div is not empty so I can hide the "header" div. But my javascript is failing.
Note: span should not have id, only the div.
<div id="header">
<label>This is a header</label>
</div>
<div id="myDiv">
<label>My Label</label>
<span>Dog</span>
</div>
Javascript:
function hideHeaders(){
var myDiv = document.getElementById('myDiv');
var x = roadDiv.getElementsByTagName('span');
if(x.value == ""){
document.getElementById('header').style.display = "none";
}
A number of corrections need to happen in your code. First, getElementsByTagName
returns a NodeList
so you need to access each individual item by index like
var x = document.getElementsByTagName('span')[0];
Also, roadDiv
is undefined and you should use document
or a parent container for above.
Next, for span
elements you need to use innerHTML
, not value
if (x.innerHTML == "") {
function hideHeaders() { var myDiv = document.getElementById('myDiv'); var x = document.getElementsByTagName('span')[0]; if (x.innerHTML == "") { document.getElementById('header').style.display = "none"; } } hideHeaders();
<div id="header"> <label>This is a header</label> </div> <div id="myDiv"> <label>My Label</label> <span></span> </div>
最好使用===而不是==,这不会对这个代码块有很大的影响,而只是将来将您的代码样式中的任何问题元素化,并消除两个相等的参数导致的奇怪错误,但是不同类型的。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.