admin管理员组文章数量:1398808
I'm trying to hide an element based on its ID, but, I haven't been able to get it to work. I've Googled the answer but, no matter what I do, I can't seem to get it to work for me.
My code is attached below.
<!DOCTYPE html>
<html>
<!-- HTML -->
<body>
<div id="role" value="Edit">
<button> Edit </button>
</div>
</body>
<!-- Javascript -->
<script>
if(document.getElementById("role").value == 'Edit'){
document.getElementById("role").style.display = 'none';
}
</script>
</html>
I'm trying to hide an element based on its ID, but, I haven't been able to get it to work. I've Googled the answer but, no matter what I do, I can't seem to get it to work for me.
My code is attached below.
<!DOCTYPE html>
<html>
<!-- HTML -->
<body>
<div id="role" value="Edit">
<button> Edit </button>
</div>
</body>
<!-- Javascript -->
<script>
if(document.getElementById("role").value == 'Edit'){
document.getElementById("role").style.display = 'none';
}
</script>
</html>
Share
Improve this question
asked Dec 6, 2018 at 14:05
jdavid05jdavid05
2451 gold badge5 silver badges16 bronze badges
2
- 2 Please ask clear question, when you want to hide, on button click? or what exactly you wants? – user10249871 Commented Dec 6, 2018 at 14:08
- stackoverflow./questions/27131899/… - according to this, the document.getElementById("role").value can only be used if this would be an input field. – MoshiMoshi Commented Dec 6, 2018 at 14:10
3 Answers
Reset to default 2You can use the code below, you want to get an attribute and not the value.
You can use querySelector instead of getElementById if you want.
var role = document.querySelector('#role');
if(role.getAttribute('value') == 'Edit'){
role.style.display = 'none';
}
<!DOCTYPE html>
<html>
<!-- HTML -->
<body>
<div id="role" value="Edit">
<button> Edit </button>
</div>
</body>
</html>
Have you tried this?
<!DOCTYPE html>
<html>
<!-- HTML -->
<body>
<div id="role" value="Edit">
<button> Edit </button>
</div>
</body>
<!-- Javascript -->
<script>
if(document.getElementById("role").getAttribute('value') == 'Edit'){
document.getElementById("role").style.display = 'none';
}
</script>
In your example document.getElementById("role").value
is undefined. To retrieve an attribute value you should use element.getAttribute('attr')
method or element.attributes[attr].value
.
In your case it would be document.getElementById("role").attributes['value'].value
本文标签: htmlJavascript Hide element if condition is metStack Overflow
版权声明:本文标题:html - Javascript: Hide element if condition is met - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744621304a2616042.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论