有条件地隐藏div元素[关闭]

问题描述 投票:-4回答:2

我是CSS和javascript的新手,所以需要一些帮助。在我的页面上,如果存在特定的html字符串,则需要隐藏div元素。这是我需要的:

    If "some html string" is present then hide <div id="some_id">

我尝试了以下代码,但没有运气:

if (document.getElementByClassName(`div class that contains my text`).innerText === 'Some Text') {
    document.getElementById(`hide_this_div`).style.display = 'block'
}
javascript css
2个回答
0
投票

我没有woocommerce的经验,但是如果您可以编写普通的CSS,则可以利用CSS的:empty选择器来实现所需的样式。您可以了解有关:empty选择器here的更多信息。

.container-element:empty {
  display: none;
}

而且,它仅在现代浏览器中受支持,因此请谨慎使用。


0
投票

你好!

实际上很容易做到,您可以通过doind实现目标:

// We verify it the wanted element exist by your given class name
// (.getElementsByClassName returns a kind of *'List'*.
// So we need to verify the length of it)

if (document.getElementsByClassName(`question-hyperlink`).length != 0) {
    document.getElementById(`some_id`).style.display = 'none'
    // Setting the display to 'none' will hide it!
}

如果您需要通过其中的文本内容进行验证,则可以像这样进行调整:

if (document.getElementById(`some-id`).innerText === 'Your text') {
    document.getElementById(`other-id`).style.display = 'block'
}
© www.soinside.com 2019 - 2024. All rights reserved.