Search for text with javascript inside a div class [closed]

◇◆丶佛笑我妖孽 提交于 2020-01-13 06:17:08

问题


I want to make a script in which I can search for a certain string automatically (no text box or anything, I want to press on a button and it searches for the word "bear" for example inside a) using "document.getElementByClassName"...my C# dev brain started to go for something like "content" or "contains" but I failed terribly...can anyone help me with an example code?

Thanks in advance :)


回答1:


I'd suggest using jquery to easily get the elements by class name and identify those with the search value. Something like:

var searchValue = "bear";

$(".ClassName").each(function(){
  if($(this).html().indexOf(searchValue) > -1){
     //match has been made
  }
});

if you are restricted to vanilla javascript, here is an example:

var els = document.getElementsByClassName("ClassName");
var searchValue = "bear";

for(var i = 0; i < els.length; i++){
  if(els[i].innerHTML.indexOf(searchValue) > -1){
    //match has been made   
  }
}

I think what you are really looking for is the comparitor String.indexOf(SearchValue) > -1, which will identify if the content of the element is a match for the string you are looking for. Note that it is case-sensitive.




回答2:


You're looking for String.indexOf(string). JavaScript indexOf.

You can do something like this:

var elements = document.getElementsByClassName('class'); // get the elements

// loop through the elements
for (var i = 0; i < elements.length; i++) {
    if (elements[i].innerHTML.indexOf(search) > -1) {
        alert('found'); // popup
    }
}


来源:https://stackoverflow.com/questions/21860663/search-for-text-with-javascript-inside-a-div-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!