Aaron
Aaron

Reputation: 11693

Accessing an item of an array with jquery?

How would I access the div with a text node of 2?

<script>
$(document).ready(function() {
  alert($('.content').length);

  $('.content').click(function(e) {
// ...
  })
});
</script>

<div class='content'>1</div>

<div class='content'>2</div>

<div class='content'>3</div>

<div class='content'>4</div>

Upvotes: 0

Views: 85

Answers (5)

tvanfosson
tvanfosson

Reputation: 532745

Depends on whether that's your only HTML or not. If your items only contain single digits, contains will work. If not, you'll need to filter based on the content.

$('.content').filter( function() { return $(this).text() == '2'; } )
             ...

On the other hand if you just want the second element, regardless of content, you can use eq().

$('.content').eq(2)
             ...

Upvotes: 1

arb
arb

Reputation: 7863

You'd want to use the filter() command of jQuery. Try this:

$(document).ready(function () {
    $('div.content').filter(function () {
        return $(this).text() == '2'
    }).css('background-color', 'red');
});

Upvotes: 0

Rafay
Rafay

Reputation: 31043

try

$("div :contains(2)").....

DEMO

Upvotes: 0

Rob W
Rob W

Reputation: 349252

Use .filter() in conjunction with .text() to get a jQuery object which contains all elements whose text content equals 2 (rather than :contains, which also matches elements which are not onyl composed of 2 characters)

var divContaining2 = $('.content').filter(function(){
     return $(this).text() == "2";
})


Use the .eq() method to get the __th element which matches the selector:

var divs = $('.content'); // Contains all `.content` elements.
var div2 = divs.eq(2);    // Get the second, returns a jQuery object

// If you want the DOM element:
var div2DOM = divs2[0];   // Alternative method: `divs2.get(0)`

Upvotes: 1

Abe Miessler
Abe Miessler

Reputation: 85126

Try this

var myDiv = $('div:contains("2")');

Upvotes: 0

Related Questions