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