the1900
the1900

Reputation: 535

JQUERY change text or value of child element in parent element

I make some code width jquery My goal is add lists under the #pivot and above <li><a href="#">bottom</a></li> How to do??

When I tried like this the only <li><a href="#"></a></li> added without text "new row"

Please teach me

HTML

<li><a href="#">top</a></li>
<li id="pivot"><a href="#">Pivot</a></li> 
<li><a href="#">bottom</a></li>

Javascript

var dom = '<li><a href="#"></a></li>';
$('a',dom).text('new row');
$('#pivot').after(dom);

Upvotes: 0

Views: 2787

Answers (2)

Ram
Ram

Reputation: 144689

That's because you are creating a jQuery object from a string but you don't store/use the created elements.

$(dom) // parse the string and create a jQuery object
   .find('a') // find the `a` descendants 
   .text('new row') // update their textContent
   .end() // get the previous jQuery collection
   .insertAfter('#pivot'); // insert the collection after `#pivot` element

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

dom is not a live node. It is just string..

If you create a jquery object out of it first, it will work

var dom = $('<li><a href="#"></a></li>');
$('a',dom).text('new row');
$('#pivot').after(dom);

Upvotes: 1

Related Questions