Arjun
Arjun

Reputation: 1279

Insert an element in between divs that have the same class

I have a page having this structure :: consecutive divs have the same class but each of its child div has a unique id.

<div class = 'samediv'>
    <div id = 'onediv'></div>
</div>
<div class = 'samediv'>
    <div id = 'twodiv'></div>
</div>
<div class = 'samediv'>
    <div id = 'thirddiv'></div>
</div>

Now on clicking the unique div, how can I insert another div/element after its parent.

For example, on clicking onediv, I want a div (say, unique) in between onediv's parent and twodiv's parent.

The structure then becomes:

<div class = 'samediv'>
    <div id = 'onediv'></div>
</div>
<div id = "unique">
</div>
<div class = 'samediv'>
    <div id = 'twodiv'></div>
</div>
<div class = 'samediv'>
    <div id = 'thirddiv'></div>
</div>

Upvotes: 0

Views: 128

Answers (4)

user2063626
user2063626

Reputation:

Try this

example :

$("#onediv").click(function () {
    $(this).parent().append('<div id = "unique"></div>')
})

required

$(".samediv > div").click(function () {
    $(this).parent().append('<div id = "unique"></div>')
})

Upvotes: 0

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35963

try this code:

$('.samediv').click(function(){
   $(this).parent().after('<div id = "unique"> </div>');
});

Upvotes: 0

K D
K D

Reputation: 5989

$("div.samediv > div").click(function(){
     $(this).parent().after("<div id='unique'></div>");
});

Upvotes: 1

VisioN
VisioN

Reputation: 145368

$(".samediv > div").on("click", function() {
    $("<div />", { id: "unique" }).insertAfter(this.parentNode);
});

Note, that instead "unique" there should be something really unique.

DEMO: http://jsfiddle.net/4MRwZ/

Upvotes: 4

Related Questions