问题
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