Reputation: 43
In JQuery ¿how can I append an img inside a div element in every second child of every div with the same class? I have this code and I want to insert a div tag between the h5 and p tags. The h5 tags are generic, they don't have any class or ID to reference, only their parent with tab-pane class.
<div class="tab-pane">
<h5></h5>
/*Here must be the new div in every tab-pane: <div><img></div>*/
<p></p>
<div></div>
<ul></ul>
</div>
<div class="tab-pane">
/*same content as before*/
</div>
<div class="tab-pane">
/*same content as before*/
</div>
<div class="tab-pane">
/*same content as before*/
</div>
So I tried this:
var paneWrap = document.createElement("div");
$(".tab-pane:nth-child(2)").append(paneWrap);
However the result was:
<div class="tab-pane">
<h5></h5>
<p></p>
<div></div>
<ul></ul>
</div>
<div class="tab-pane">
<h5></h5>
<p></p>
<div></div>
<ul></ul>
<div></div> /*THE NEW DIV IS HERE!*/
</div>
<div class="tab-pane">
<h5></h5>
<p></p>
<div></div>
<ul></ul>
</div>
<div class="tab-pane">
<h5></h5>
<p></p>
<div></div>
<ul></ul>
</div>
Then I tried this:
var paneWrap = document.createElement("div");
$(".tab-pane > h5:nth-child(1)").append(paneWrap);
However in this case inside the h5 is the new div. Any ideas? tks!
Upvotes: 1
Views: 89
Reputation: 2731
Here is what is happening :
var paneWrap = document.createElement("div");
$(".tab-pane:nth-child(2)").append(paneWrap);
When you use the selector .tab-pane:nth-child(2)
, it selects all the .tab-pane
elements which are second child. And after finding those elements, the div
you created using paneWrap
gets appended.
But when you use .tab-pane > h5:nth-child(1)
for selector, it selects the h5
elements and appends the div
inside it.
Now, to insert an element after/ before an element, here are the approaches :
var paneWrap = document.createElement("div"); //creating div element
For inserting after h5 :
$(".tab-pane > h5:nth-child(1)").after(paneWrap);
or
$(paneWrap).insertAfter(".tab-pane > h5:nth-child(1)");
For inserting before p tag :
$(".tab-pane > p:nth-child(2)").before(paneWrap);
or
$(paneWrap).insertBefore(".tab-pane > p:nth-child(2)");
Upvotes: 1
Reputation: 97672
Since you select the element you want the div to come after, you should use .after()
var paneWrap = document.createElement("div");
$(".tab-pane > h5:nth-child(1)").after(paneWrap);
h5 + div{
width:1em,height:1em;border:1px red solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab-pane">
<h5></h5>
<p></p>
<div></div>
<ul></ul>
</div><div class="tab-pane">
<h5></h5>
<p></p>
<div></div>
<ul></ul>
</div><div class="tab-pane">
<h5></h5>
<p></p>
<div></div>
<ul></ul>
</div><div class="tab-pane">
<h5></h5>
<p></p>
<div></div>
<ul></ul>
</div>
Upvotes: 1