javascript 隐藏包含特定文本的 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46790860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hide div that contains specific text
提问by Jilco Tigchelaar
I want to hide a div based on the text inside. In the example below I want to hide the ones with "Handtekening" and the one with "Thuis". I prefer to do that with CSS. Is that possible?
我想根据里面的文字隐藏一个 div。在下面的示例中,我想隐藏带有“Handtekening”和带有“Thuis”的那些。我更喜欢用 CSS 来做到这一点。那可能吗?
The class names of the divshave to be the same...
的类名divs必须相同...
<div class="test">
Pakket
</div>
<div class="test">
Handtekening
</div>
<div class="test">
Thuis
</div>
If not possible with CSS, how can it be done with JavaScript?
如果使用 CSS 无法实现,那么如何使用 JavaScript 来实现?
采纳答案by o01
Here's an easy vanilla Javascript solution:
这是一个简单的 vanilla Javascript 解决方案:
let divs = document.getElementsByClassName('test');
for (let x = 0; x < divs.length; x++) {
let div = divs[x];
let content = div.innerHTML.trim();
if (content == 'Handtekening' || content == 'Thuis') {
div.style.display = 'none';
}
}
Remember to include the script at the end of your HTML page (right before the </body>tag).
请记住将脚本包含在 HTML 页面的末尾(就在</body>标记之前)。
回答by DreamWave
If you have control over the HTML output and have no problems with the text document getting twice as big, you can duplicate the content of each of those divs. Otherwise JavaScript is the way to go. Here is the CSS solution:
如果您可以控制 HTML 输出并且文本文档变大两倍没有问题,那么您可以复制每个 div 的内容。否则 JavaScript 是要走的路。这是CSS解决方案:
<div class="test" content="Pakket">
Pakket
</div>
<div class="test" content="Handtekening">
Handtekening
</div>
<div class="test" content="Thuis">
Thuis
</div>
Then use the selector for an attribute containing a string:
然后将选择器用于包含字符串的属性:
div[content~=Thuis] { display:none; }
The one above will match when "Thuis" is contained in the text as a separate word. If you want to match any occurrence of the string, you should use:
当“Thuis”作为单独的词包含在文本中时,上面的将匹配。如果你想匹配任何出现的字符串,你应该使用:
div[content*=and] { display:none; }
回答by cн?dk
No, it won't be possible with pure CSS. You need to use JavaScript to do it.
不,纯 CSS 是不可能的。你需要使用 JavaScript 来做到这一点。
This is code you can use for that:
这是您可以使用的代码:
var divs = document.querySelectorAll(".test");
Array.from(divs).forEach(function(div) {
if (div.textContent.indexOf("Handtekening") >= 0 || div.textContent.indexOf("Thuis") >= 0) {
div.style.display = "none";
}
});
var divs = document.querySelectorAll(".test");
Array.from(divs).forEach(function(div) {
if (div.textContent.indexOf("Handtekening") >= 0 || div.textContent.indexOf("Thuis") >= 0) {
div.style.display = "none";
}
});
<div class="test">
Pakket
</div>
<div class="test">
Handtekening
</div>
<div class="test">
Thuis
</div>
回答by Deathstorm
You could do the easy thing of hiding the elements with a second class.
您可以轻松地将元素隐藏起来class。
So let's say we'll add the class="hidden".
因此,假设我们将添加class="hidden".
See the example below:
请参阅以下示例:
.test {
color: blue;
}
.hidden {
display: none;
/* or visibility: hidden; */
}
<div class="test">
Pakket
</div>
<div class="test hidden">
Handtekening
</div>
<div class="test hidden">
Thuis
</div>
By adding the second classwe're able to make a selection of which <div>element you'd like to show and which not.
通过添加第二个元素,class我们可以选择<div>要显示的元素和不显示的元素。
回答by Ilmari Karonen
Here's one more solution:
这是另一种解决方案:
Array.from( document.querySelectorAll('div.test') )
.filter( node => /\b(Handtekening|Thuis)\b/i.test(node.textContent) )
.forEach( node => node.style.display = 'none' );
<div class="test">
Pakket
</div>
<div class="test">
HANDTEKENING
</div>
<div class="test">
Test thuis blah blah
</div>
The main difference from chsdk's solutionis that I'm using a single regexp testinstead of multiple .indexOf()calls. IMO this is cleaner, more flexible and possibly more efficient as well.
与chsdk 解决方案的主要区别在于我使用的是单个正则表达式测试而不是多个.indexOf()调用。IMO 这更干净、更灵活,也可能更高效。
The \banchors in the regexp match word boundaries, so that e.g. "Thuis test"is matched but "Thuistest"is not. I suspect this is what the OP wants, but if not, the \banchors can easily be removed and/or replaced with something else. For example, the regexp:
\bregexp 中的锚点匹配单词边界,因此 eg"Thuis test"匹配但"Thuistest"不匹配。我怀疑这就是 OP 想要的,但如果不是,\b锚点可以很容易地被移除和/或替换为其他东西。例如,正则表达式:
/^\s*(Handtekening|Thuis)\b/i
would match only if the words "Handtekening" or "Thuis" occur at the beginning of the content (possibly after some whitespace). Replacing the second \bwith \s*$would also require there to be nothing (except possibly whitespace) after the matched word.
仅当“Handtekening”或“Thuis”出现在内容的开头(可能在一些空格之后)时才会匹配。将第二个替换为\bwith\s*$还要求匹配的单词之后没有任何内容(可能除了空格)。
The iflag at the end of the regexp literal makes the matching case-insensitive. If not desired, the ican simply be removed. I wanted to include it for illustrative purposes, though.
正i则表达式文本末尾的标志使匹配不区分大小写。如果不需要,i可以简单地将其移除。不过,我想将它包含在内以进行说明。
Ps. Some older browsers (such as, notably, Internet Explorer) may not support the ES6 arrow functionsand the Array.from()method used in the code above. If compatibility with such old browsers is desired, here's an alternative implementation free from any such newfangled stuff:
附言。一些较旧的浏览器(例如,特别是 Internet Explorer)可能不支持 ES6箭头函数和Array.from()上面代码中使用的方法。如果需要与此类旧浏览器兼容,这里有一个没有任何此类新奇事物的替代实现:
var nodes = document.querySelectorAll('div.test');
for (var i = 0; i < nodes.length; i++) {
if ( /\b(Handtekening|Thuis)\b/i.test(nodes[i].textContent) ) {
nodes[i].style.display = 'none';
}
}
<div class="test">
Pakket
</div>
<div class="test">
HANDTEKENING
</div>
<div class="test">
Test thuis blah blah
</div>
AFAICT, this should be compatible with IE down to version 9, and of course with all modern browsers as well.
AFAICT,这应该兼容 IE 到版本 9,当然也兼容所有现代浏览器。
回答by Nenad Vracar
To select elements based on text you can use js and check if text is equal to ones you want to hide. If it is you can set display property to noneto hide that element.
要根据文本选择元素,您可以使用 js 并检查文本是否等于要隐藏的元素。如果是,您可以将 display 属性设置none为隐藏该元素。
[...document.querySelectorAll('.test')].forEach(function(e) {
if (['Handtekening', 'Thuis'].includes(e.textContent.trim())) {
e.style.display = 'none'
}
})
<div class="test">
Pakket
</div>
<div class="test">
Handtekening
</div>
<div class="test">
Thuis
</div>
回答by Rajaprabhu Aravindasamy
You can do it just like this,
你可以这样做,就像这样
let filteredOut = ['Handtekening', 'Thuis'];
Array.from(document.querySelectorAll(".test")).forEach((elm) => {
if(filteredOut.includes(elm.textContent.trim())) elm.style.display = "none";
});
DEMO
演示
- Collect the values that are needs to be filtered out in a separate array.
- Iterate over all the elements and check its value presents in the filter array.
- If it exists, just hide it.
- 收集需要在单独数组中过滤掉的值。
- 迭代所有元素并检查其值出现在过滤器数组中。
- 如果它存在,只需隐藏它。
Side Note:You can use a class to add to the caught elements instead of inserting inline styles.
旁注:您可以使用类添加到捕获的元素,而不是插入内联样式。
回答by Renzo Calla
You can do it with JavaScript:
你可以用 JavaScript 做到:
var elements = document.getElementsByClassName('test');
for(var i = 0; i<elements.length; i++){
if(elements[i].innerText==='Handtekening' || elements[i].innerText==='Thuis'){
elements[i].style.display = 'none';
}
}
<div class="test">
Pakket
</div>
<div class="test">
Handtekening
</div>
<div class="test">
Thuis
</div>
回答by Yerlan
Here's pure JavaScript solution:
这是纯 JavaScript 解决方案:
// Define your variables
var objectsToCheck = document.getElementsByClassName("test");
var hideText = "Pakket";
// Loop through your div objects
[].forEach.call(objectsToCheck, function (o) {
// Check if text appears in div under class "test"
if(o.innerText.toLowerCase() == hideText.toLowerCase()){
o.style.display = "none";
}
});
回答by Rajesh
You can use querySelectorto fetch elements and use element.classList.toggleto add/remove a class that will hide the value.
您可以用于querySelector获取元素并用于element.classList.toggle添加/删除将隐藏值的类。
document.querySelector('#btn').addEventListener('click', function(){
var text = document.querySelector('#txt').value.trim();
var list = document.querySelectorAll('.test');
for(var i = 0; i< list.length; i++) {
list[i].classList.toggle('hide', list[i].textContent.trim() === text);
}
})
.hide {
display: none;
}
<div class="test">
Pakket
</div>
<div class="test">
Handtekening
</div>
<div class="test">
Thuis
</div>
<input type='text' id='txt' />
<button id='btn'>Hide Div</button>

