merch89 merch89 - 8 months ago 30
Javascript Question

Matching multiple keywords using contains() in jQuery

Currently matching a specific keyword using contains(). How can i expand this to include multiple keywords?
have tried using the || (or) operator, but no joy.

<!-- Product names include Apple iPad, Acer Iconia, Lenovo Thinkpad -->

<h1 id="pbtitle">Apple iPad 3</h1>


<div class="install_option" style="display:none;">
<div style="box-sizing:border-box; float:left;">
<a href="https://www.exmaple.com/acc" target="_blank">
<h3 style="font-weight:bold;">Would you like to view accessories?</h3>
</a>
</div>

</div>


$(".install_option").each(function() {
if($("h1#pbtitle:contains:contains('Acer' || 'Lenovo' || Apple )").length>0){
$('.install_option').css('display','block');
}
});

Answer Source

Use JavaScript function indexOf()
Working example jsfiddle

var options = ['Acer','Lenovo','Apple']; // options that you want to look for
var text = $("#pbtitle").text();         // string where you want to look in

options.forEach( function( element ) {
    if ( text.indexOf( element ) != -1 ) {    // if its NOT -1 (-1 = not found)
      alert( 'found' );                       // then we found it .. do your magic
    }
})