Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  70] [ 1]  / answers: 1 / hits: 16494  / 10 Years ago, tue, february 18, 2014, 12:00:00

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 :)


More From » search

 Answers
20

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.


[#72450] Monday, February 17, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
masonm

Total Points: 167
Total Questions: 87
Total Answers: 103

Location: Rwanda
Member since Wed, Jun 8, 2022
2 Years ago
masonm questions
;