Reputation: 179
I am trying to append a string to a page. If I write $('.txt')
in the console, it returns:
If I write $('.txt')
, it returns the first .txt
.
If I write $('.txt').append('<div><span>TEEST</span></div>')
in the console, it appends "TEEST" to all .txt
s in the page.
But if I write $('.txt')[0].append('<div><span>TEEST</span></div>')
it returns:
Why is this? How I can append to a specific DOM element?
Upvotes: 4
Views: 357
Reputation: 59323
[0]
gets the first actual DOM element—not the jQuery object. append
is a jQuery-specific function, so you can't call it on regular DOM elements (like those that are returned from getElementById
).
You want eq
:
$('.txt').eq(0).append('<div><span>TEEST</span></div>');
You could also use the :first
selector:
$('.txt:first').append('<div><span>TEEST</span></div>');
Upvotes: 5