开发者

jQuery: take existing HTML, modify one node, then reinject

开发者 https://www.devze.com 2022-12-10 12:08 出处:网络
I have a blob of HTML that I\'m retrieving using simple jQuery selectors, something like the following:

I have a blob of HTML that I'm retrieving using simple jQuery selectors, something like the following:

<div id="stuff">
 <ul> 
   <li>some</li>
   <li class="ninja">stuff</li>
 </ul>
</div>

I'm basically doing:

var myblock = $("#stuff").html();

now I want to inject an additio开发者_JS百科nal li element to the bottom of that li list with very similar attributes to the li above it, but i want to change the class ninja to class samurai.

What's the best way of going about that with jQuery?


Simply select the <ul> and append the <li> to it

$("#stuff ul").append('<li class="samurai">stuff</li>');

If you actually wanted to copy the last <li> element, change the class then add to the list, then you could do something like this

var ul = $("#stuff ul");
ul.append(ul.find('li:last').clone().removeClass().addClass("samurai"));

pass true into clone() if you also want to copy event handlers too.

The problem with taking a whole chunk of HTML, changing an element and then reinserting is that any event handlers set up on elements that will be replaced when you reinsert the HTML will be lost, so it's more elegant/ and less cumbersome/intrusive to simply manipulate the part of the DOM that you need to.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号