0

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>
1
  • If you mean when you click on it, use this or e.target in your click function: alert($(this).html()). Commented Nov 2, 2011 at 19:12

5 Answers 5

1

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)
             ...
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Won't this get the div at index 2 regardless of what text it contains?
@AbeMiessler Updated answer to reflect the question.
0

Try this

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

2 Comments

Except this also matches <div class='content'>12</div>
This is true. It does not perform an exact match. If he needs that then your method is best.
0

try

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

DEMO

Comments

0

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');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.