-1

I'm a nub in jQuery and javascript in general, so this must be a beginners question.

This line works for me, foo is not empty:

var foo = $("#hello").find("option").filter (function(){return $(this).text() == "BAR";});

This one in the same spot doesn't (foo undefined):

var foo = $("#hello").find("option").filter (function(){return $(this).attr("innerText") == "BAR";});

The only difference is using .text() vs .attr("innerText"). Why the latter doesn't work for me?

9
  • how is your HTML? Post it, please.
    – celerno
    Aug 4, 2014 at 19:19
  • 4
    Do you have an attribute called innerText? Also, does #hello without quotes in your selector really work? And the quotes are BAR are not the same quotes.
    – tymeJV
    Aug 4, 2014 at 19:19
  • Because innerText is a Microsoft concoction?
    – j08691
    Aug 4, 2014 at 19:20
  • As tymeJS mentioned, probably the element doesn't have an attribute innerText. jQuery's text() method encapsulate the .innerText from vanilla js, such as .html() encaspulate innerHTML. Aug 4, 2014 at 19:21
  • 1
    innerText is a property, you'd get that with jQuery's prop() method, but why would you when you can use text() instead, which is cross browser (innerText is not)
    – adeneo
    Aug 4, 2014 at 19:23

2 Answers 2

3

.attr() finds HTML attributes attached to the DOM element, it's not looking for the DOM element's JavaScript attributes like innerHTML or innerText. To find such attributes, you need to access the DOM element inside the jQuery object that the selector returns, or in this case, the this reference itself, such as:

var foo = $('#hello').find("option").filter (function(){return this.innerText == “BAR";});

As pointed out by others, this is not advised since it can lead to unexpected behavior and it's also not cross-browser compatible. Just use .text() instead.

1
  • 2
    (It should be noted that using innerText is still not advisable.) Aug 4, 2014 at 19:23
1

.attr() is looking for the attribute innerText on the node. It will give you undefined except if you node look like that :

<div innerText="test"></div>

Maybe your are mixing yourself with .prop('innerText') which get the property innerText of the node. That is the same as .text() except that .text() is safer since jQuery counter compatibility issues..

If you are interested by how jQuery get the text no matter which browser you are, here the relevant code

Not the answer you're looking for? Browse other questions tagged or ask your own question.