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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With