0

Running this on chrome console (in Reddit.com)

$('.title')

Returns array like object:

n.fn.init[10]
0:span.selected.title
1:div.title
2:div.title
3:p.title
4:
:
document
length
:
10
prevObject
:
n.fn.init[1]
selector
:
".title"
__proto__
:
Object[0]

I want to select one of them and use Jquery mehtod (text(), html()). But this

$('.title')[4].text();

Returns error:

VM1223:1 Uncaught TypeError: $(...)[4].html is not a function
    at <anonymous>:1:16
yask
  • 3,918
  • 4
  • 20
  • 29
  • 1
    Accessing a jQuery object by bracket notation returns a DOMElement - hence the `html()` method is not available. Use the `eq()` method instead. See the question I marked as a duplicate for more information. – Rory McCrossan Jan 04 '17 at 08:31
  • @RoryMcCrossan Thanks! Got it. – yask Jan 04 '17 at 08:33
  • @RoryMcCrossan have any idea why `text()` as getter is only JQ getter method that returns all and not just the first in set? – charlietfl Jan 04 '17 at 08:34
  • I guess $($('.title')[4]).html() is what you are looking for. Wrap $('.title')[4] in $ to make it jquery element and to use jquery methods on it. – Nikhil Maheshwari Jan 04 '17 at 08:35
  • @NikhilMaheshwari no, just no. Use `eq()`. Don't get a jQuery object, turn it in to a DOMElement then back in to a jQuery object. – Rory McCrossan Jan 04 '17 at 08:35
  • @charlietfl I wish I did. It's a bit non-standard. Might be worth a pull request for consistency's sake :) – Rory McCrossan Jan 04 '17 at 08:36
  • @RoryMcCrossan has been like that forever, and always a mystery to me since as you say it is inconsistent with all the other methods – charlietfl Jan 04 '17 at 08:37
  • @RoryMcCrossan : Get your facts straight man, just read https://www.sitepoint.com/speed-test-this-get-eq/ before putting such a strong opinion. eq is much slower than wrapping. – Nikhil Maheshwari Jan 04 '17 at 08:41
  • How is that speed test even related to what you suggested? Also, if performance is that much of an issue, then you shouldn't be using jQuery at all. – Rory McCrossan Jan 04 '17 at 08:42
  • @RoryMcCrossan : The performance matters a lot and there is always a tradeof between speed and usability. Anyways, I guess you got my point. I would suggest you to look into language internals too before giving a strong opinion and its good if you can back your answers with some facts. – Nikhil Maheshwari Jan 04 '17 at 08:54
  • @RoryMcCrossan : if its being difficult for you to understand my post. I can make you understand in simple words. Feel free to reach me ? – Nikhil Maheshwari Jan 04 '17 at 08:59

0 Answers0