0

I would like my code to work like this: There are few DIVs with similar ID and similar content. When I click on CLICK button i need already existing DIV id="object" to prepend to parent div of the click button. My code works just for the first of DIVs.

HTML

<div id="article">
<p>...CONTENT</p>
<div class="click">CLICK</div>
</div>

<div id="article">
<p>...CONTENT</p>
<div class="click">CLICK</div>
</div>

CSS

#article{
    width: 100%;
    height: 200px;
    background: gray;
    color: white;
}

.click{
    cursor: pointer;
    color: red;
}

#object{
    width: 100%;
    height: 100px;
    background: red;
}

Jquery

$(".click").click(function(){
    $('#object').prependTo("#article");
});

JSFiddle

Petr Rajchert
  • 59
  • 1
  • 1
  • 5

1 Answers1

0

Ok, first, having the same ID for multiple elements is bad, bad, bad. See Why is it a bad thing to have multiple HTML elements with the same id attribute?. You can use classes instead

<div class="article">
<p>...CONTENT</p>
<div class="click">CLICK</div>
</div>

<div class="article">
<p>...CONTENT</p>
<div class="click">CLICK</div>
</div>

To prepend to the closest div in question, you can use jQuery closest() with $(this) which will be the 'clicked' div when it enters the handler

$(this).closest('.article').prepend($('#object'));

See it working here

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53