jdavid05
jdavid05

Reputation: 245

Javascript: Hide element if condition is met

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

Answers (3)

mickiewicz
mickiewicz

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

Lucas Reis
Lucas Reis

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

Nico Savini
Nico Savini

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

Related Questions