1

I have a series of divs on my page and am having trouble selecting each div containing a specific string when the string is kept in an array. For example, if the array = ['foo', 'qux'], I would like to be able to select the div containing 'foo', and the div containing 'qux'.

<div class="word word1">foo</div>
<div class="word word2">bar</div>
<div class="word word3">baz</div>
<div class="word word4">qux</div>

The script

array =  ['foo', 'qux'];
for (var i = 0; i < array.length; i++) {
  array_text = array[i];
  alert( $( "div:contains(array_text)" ).text() );
}

I have also used this script without success:

correct_matches =  ['foo', 'qux'];
$.each(correct_matches, function(index, value){
  alert( $( "div:contains(value)" ).text() );
  }
);

I am using the alert only to ascertain whether or not the $( "div:contains(array_text)") selector is working properly. The selector is where I am running into problems: $( "div:contains('bar')" ) works as expected. Once I use the array_text variable, I get an alert with an empty string. Any suggestions? Thank you.

user3291025
  • 997
  • 13
  • 20
  • You need to escape the selector to include a variable, otherwise it's just looking for `contains "value"` not the variable `value`. – Sterling Archer May 30 '14 at 19:02

2 Answers2

1

Check this FIDDLE.

You were testing if the text array_text was contained by the div.

I'm not sure if this is the most optimal, but it works.

jQuery version:

$(function () {

    var array = ['baz', 'qux'];
    for (var i = 0; i < array.length; i++) {
        array_text = array[i];
        $('div').each(function () {
            if ($(this).text() == array_text) {
                alert(array[i]);
                // do more stuff with $(this) (which is the div)
            }
        });
    }
});
cr0ss
  • 877
  • 5
  • 20
  • Works exactly as I wanted, and more, because now I can do more stuff with $(this), which is my next step, many thanks. – user3291025 May 30 '14 at 19:28
0
var array =  ['foo', 'qux'];
var elements = document.querySelectorAll(".word"); // get all elements of class word

for(var i =0;i <array   .length;i++ ) // first loop for your array
for(var ii=0;ii<elements.length;ii++) // second loop for the elements in the collection
if(array[i] == elements[ii].innerHTML){ // check for matches
  elements[ii]; // this is the handle to the html element
}

Run through both collections and check when there is a match between the 2 collections.

CyberFox
  • 780
  • 6
  • 24