Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 876
user3324529 Avatar asked Dec 11 '25 03:12

user3324529


1 Answers

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.

like image 171
Will P. Avatar answered Dec 13 '25 15:12

Will P.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!