Body
Body

Reputation: 3688

Create a Parent div for multiple child divs - Jquery

My code goes like this,

<div class="sExample">
    <div class="child1 one">...</div>
    <div class="child2 one">...</div>

    <table>...</table>
    <div class="child3">...</div>
</div>

I want to include a parent div only for the .child1 and .child2 targeting class .one. I tried the jQuery .wrap method, but its adding parent div for each items.

Please help me do this.

Upvotes: 3

Views: 5717

Answers (3)

YD1m
YD1m

Reputation: 5895

Use this for wrap each element in it own container:

$('.one').wrap('<div></div>');

Upvotes: 1

jawerty
jawerty

Reputation: 155

Why not use appendTo() to move the element. Also, if possible, try using an id for the parent div .sExample it would be easier to manipulate in code.

document.getElementsByClassName('.child1 .one')[0].appendTo(document.getElementsByClassName('.sExample')[0])

You would probably have to iterate over your classes if you have multiple classes with the same name. Once again, I suggest moving to ids if you can.

Upvotes: 0

Jason P
Jason P

Reputation: 27022

Assuming you want the result to look like this:

<div class="sExample">
    <div>
        <div class="child1 one">...</div>
        <div class="child2 one">...</div>
    </div>

    <table>...</table>
    <div class="child3">...</div>
</div>

Use wrapAll() instead of wrap():

$('.one').wrapAll('<div>');

Upvotes: 7

Related Questions