开发者

jquery - get first occurence of selection

开发者 https://www.devze.com 2023-03-31 15:13 出处:网络
How can i determine iffirst occurance (element 0) ofcontains 开发者_运维知识库text \"No Errors\"

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


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:

  • :first.
  • eq().
  • toLowerCase().
  • indexOf().


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)


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号