简体   繁体   中英

tag next to a label in javascript

I do not have the luxury of using jQuery, I want to hide the span tag in certain conditions using Javascript and the span tag does not have an id.

"<label name="lcity" id="lcity" for="city" class="formLabel" title="City">City:</label>
<span class=spanclass>*</span>

I tried something like this and did not work:

var countyFieldLabel = document.getElementById('lcity').nextElementSibling;
countyFieldLabel.visibility="hidden";

Can anyone suggest something please?

Thanks

You almost go it right:-

Visibility is not an element attribute instead it is a style attribute.

use

 countyFieldLabel.style.visibility="hidden";

Instead of

countyFieldLabel.visibility="hidden";

Fiddle

Use nextSibling instead of nextElementSibling:

function hideSpan()
{
     var element = document.getElementById("lcity").nextSibling.style.visibility = 'hidden';      
}

HTML:

<body onload="hideSpan()">     
    <label id="lcity" for="city" class="formLabel" title="City">City:</label><span class=spanclass>*</span>       
</body>

In Addition, please remove your name attribute in label. It is not allowed.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM