简体   繁体   English

我如何将此 jquery 转换为 javascript

[英]how can i convert this jquery to javascript

how can i convert this jquery code to vanilla Javascript我如何将此 jquery 代码转换为vanilla Javascript

 $("h2:contains('" + search + "')").closest(".element").show();
 $("h2:not(:contains('" + search + "'))").closest(".element").hide();

i got the second half of the line to be closest(".element").style.display = "block" but i cant find a way for the first half to work in normal Javascript.我得到了该行的后半部分closest(".element").style.display = "block"但我找不到前半部分在正常 Javascript 中工作的方法。 I am creating a live search function to match the text in the search input to match the h2 .我正在创建一个实时搜索功能来匹配搜索输入中的文本以匹配h2 if they match it will display the content if not the content will display as none.如果它们匹配,它将显示内容,否则,内容将显示为无。

In Jquery contains gives you a string of text to look for.在 Jquery 中包含给你一个要查找的文本字符串。

So here you need to get all the h2 tag and search in their text.所以在这里你需要获取所有的h2标签并在它们的文本中进行搜索。

As h2 elements don't have a value, you should use innerHTML and then instead of contains, you should use includes method.由于h2元素没有值,您应该使用innerHTML,然后您应该使用includes方法而不是包含方法。

var allHTwos= document.getElementsByTagName('h2');
for (i=0; i<allHTwos.length; i++) {
    var gh = allHTwos[i];
    var ts = gh.innerHTML;
    if(ts.includes(search)){
// Do your hide/unhide here
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM