开发者

Append HTML tag to Class with jQuery

I want to add an <ul></ul> tag instead a class <div class='box'></div> I use appendTo() in this way

$('<ul>').appendTo('.box');

But I get:

<div class="box"><li>You did not enter your first name</li><ul></ul></div>

And of couse should i get:

<div class="box"><ul><li>You did not enter your first name</li>开发者_开发知识库</ul></div>


If the li is already in the div (which would be invalid html):

$('.box li').wrapAll('<ul></ul>');

Should work.

If the li is added after the ul is appended:

$('<li />').text('whatever').appendTo('.box ul');

The fact that you're using append() suggests that the li is already present though, which seems a little odd.

API references:

  • wrapAll(),
  • appendTo(), explaining why append inserts the ul after the li, which seemed to surprise you.


appendTo will simply add the element at the bottom of your container, as in the code you've posted. What you want appears to be something more like

$('.box li').wrap('<ul/>');


Use wrapAll:

$('.box>li').wrapAll('<ul/>');


You're looking for:

$('.box').wrapInner("<ul />");`

http://api.jquery.com/wrapInner/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜