0

I want to ask a stupid question about jQuery. If I have:

<ul>
  <li class="ft">
   <ul class="sub"><li></li></ul>
  </li>
</ul>

I want if become:

<ul>
  <li class="ft">
   <div class="hello"><ul class="sub"><li></li></ul></div>
  </li>
</ul>

How can I add div class="hello" by jQuery?

Thanks!

0

7 Answers 7

5

Use wrap()

$('.sub').wrap('<div class="hello" />');

Reference: http://api.jquery.com/wrap/


as a sidenote: use $('.sub') instead of $('ul.sub') since is more efficient. See http://jsperf.com/jquery-class-vs-element-class

enter image description here

Sign up to request clarification or add additional context in comments.

5 Comments

Youll get a slight performance increase by changing your selector to $('ul.sub')
@Sam have you done some tests about it? my test say that .sub is faster than ul.sub
@FabrizioCalderan Yes, on the JavaScript application I work on we get a performance benefit of a few milliseconds. It is a bit of a micro-optimisation but over large front end apps it can make a noticeable difference in performance.
@FabrizioCalderan your jsperf is wrong as you are not cleaning element after wrap it, so second loop will rewrap already wrapped elements making it slower each time a little more
More accurate jsperf here, you'll see performance are quite the same: jsperf.com/jquery-class-vs-element-class/2
2

$('.sub').wrap('<div class="hello" />');

Comments

2
$('ul.sub').wrap('<div class="hello">');

Comments

0
$('li.ft').html('<div class="hello">'+$('li.ft').html()+'</div>');

1 Comment

Using that, you'll lose associated data as handlers if any
0

Use prepend

$('.ft').prepend('<div class="hello"><ul class="sub"><li></li></ul></div>');

Comments

-1

There are many ways you can achieve this in jquery. Some of them involves you using DOM traversal to reach the element just before you want to add the and use jquery to add it...jquery has extensive support for this kind of parent,child, sibbling etc traversal...

But the simplest way is to manually add the element in your html markup and the use jquery to add the class attribute programmatically...

so in your jquery you can simply dosomething like:

jquery("#someid").addclass("hello");

Hope this helps...:)

Comments

-3
$('li.ft').find('div').addClass('hello');

1 Comment

Not what the question was. The div had to be created.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.