1

This is foo that I created in the console using dom selectors:

foo
[<input type=​"text" maxlength=​"70" id=​"authCreateAcctUsernameInput" name=​"userName" autocomplete=​"off" autocapitalize=​"off" autocorrect=​"off">​]

Then, on the back of a question I just asked a few minutes ago, I learned that if I want to get the textContent of a jquery object I must use .text().

Foo has some siblings:

<fieldset>
    <label class="userName" for="authCreateAcctUsernameInput">Email Address</label>
    <input type="text" maxlength="70" id="authCreateAcctUsernameInput" name="userName" autocomplete="off" autocapitalize="off" autocorrect="off">
    <span id="authCreateAcctUsernameErrorTxt" class="errorMSG" style="display: block;">Please enter a valid email address.</span>

In order to get "Email Address" from Foo's sibling textContent I tried this:

$(foo).parent().children()[0].text()

But that returned TypeError: undefined is not a function.

This does "work":

 $(foo).parent().children()[0]
    <label class=​"userName" for=​"authCreateAcctUsernameInput">​Email Address​</label>​

The element is returned. So why can I not add .text() to get what I need, which is the string "Email Address"?

Doug Fir
  • 19,971
  • 47
  • 169
  • 299
  • 3
    When you use `[0]`, you're returning a DOM node, not a jQuery object, so then trying to use `.text()` will fail. Instead, try `.children().eq(0).text()`. Or better yet, just `$(foo).prev()`. – j08691 Sep 30 '14 at 02:51
  • Thanks for the help here that seems to have solved my problem. I've only recently started picking up JS and jquery is pretty new to me. Will look into eq() function. P.S. I can;t actually use prev() since the order of the elements will vary when this function is used throughout the site, cheers though! – Doug Fir Sep 30 '14 at 02:57

1 Answers1

6

It doesn't "return undefined" per se, it uhh, throws an exception because undefined() is invalid.

This is because .children()[0] (equivalent to .children().get(0)) returns a DOM element, not a jQuery object, and thus domElement.text evaluates to undefined.

Various forms to find the "first child" as a jQuery object/set can be found in How to select first child with jQuery?

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220