Darcyys
Darcyys

Reputation: 179

"$(...)[0].append is not a function" with jQuery

I am trying to append a string to a page. If I write $('.txt') in the console, it returns:

enter image description here

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 .txts in the page.

But if I write $('.txt')[0].append('<div><span>TEEST</span></div>') it returns:

enter image description here

Why is this? How I can append to a specific DOM element?

Upvotes: 4

Views: 357

Answers (1)

tckmn
tckmn

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

Related Questions