Reputation: 245
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>
Upvotes: 1
Views: 12463
Reputation: 289
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
Upvotes: 0
Reputation: 471
You 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>
Upvotes: 2
Reputation: 487
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>
Upvotes: 1