mustapha george
mustapha george

Reputation: 621

jquery - get first occurence of selection

How can i determine if first occurance (element 0) of contains text "No Errors"

if ($(xml).find('errors')[0].text() == 'No Errors') 
{
  do something
}

!!! edit !!!

 found it...

 if ($(xml).find('error').first().text() == 'No errors') 

Upvotes: 3

Views: 9073

Answers (4)

David Thomas
David Thomas

Reputation: 253506

Using [0] causes JavaScript/jQuery to return the DOM node, instead of the jQuery object, you might try:

if ($(xml).find('.errors:first').text() == 'No Errors') 
{
  // do something
}

Or:

if ($(xml).find('.errors').eq(0).text() == 'No Errors') 
{
  // do something
}

Both of these if statements require that the text is, not simply contains, equal to 'No Errors'.

To test that the text contains the text 'No Errors':

if ($(xml).find('.errors').eq(0).text().toLowerCase().indexOf('no errors') > -1) 
{
  // do something
}

JS Fiddle demo.

References:

Upvotes: 6

Jamiec
Jamiec

Reputation: 136239

if ($(xml).find('errors').eq(0).text() == 'No Errors') 
{
  do something
}

Upvotes: 0

jfriend00
jfriend00

Reputation: 708206

This should work:

if ($(xml).find('errors').first().text().indexOf('No Errors') != -1)
{
  do something
}

Changes:

  1. Use first() to get a jQuery object of the first matched element, not a DOM object
  2. Use indexOf() on the text to see if 'No Errors' is anywhere inside
  3. Compare to -1 to see if it's there

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 93003

Using brackets will give you the DOM element; you need the jQuery object so you can use .text() on it. To test for equality:

if ($(xml).find('errors:first').text() == "No Errors")

To test for containment:

if ($(xml).find('errors:first').text().indexOf("No Errors") > -1)

Upvotes: 1

Related Questions