最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript: Hide element if condition is met - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 2

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>

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

发布评论

评论列表(0)

  1. 暂无评论