Reputation: 17
I have used jquery to append span element after image tag. But the span element showing inside the image tage. I am moving the caption from one place to another so if i use insertafter it gets dulicated on another place. Please check with the following code and guide me to solve this
$(".wf_captionfirst").appendTo($("#articlespace img"));
Output shows
<img src="" ><span class="wf_captionfirst">adsfasdff</span></img>
Upvotes: 2
Views: 506
Reputation: 6130
You should use .insertAfter()
. This will insert the selected element after each img
.
$(".wf_captionfirst").insertAfter($("#articlespace img"));
If you want to insert at one img then you could use pseudo selectors;
$(".wf_captionfirst").insertAfter($("#articlespace img:first-of-type"));
or specify by ID or Class;
$(".wf_captionfirst").insertAfter($("#articlespace .imageContainer"));
$(".wf_captionfirst").insertAfter($("#articlespace #imageContainer"));
insertAfter doesn't duplicate the element IF there is only 1 target. Demo:
$(document).ready(function() {
$(".move").click(function() {
$(".moveMe").insertAfter(".A");
});
});
.A {
padding: 40px;
border: 1px solid blue;
}
.B {
padding: 40px;
border: 1px solid red;
}
.moveMe {
padding: 2px;
border: 1px solid black;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="move">Move</button>
<div class="moveMe">
Test
</div>
<div class="A">
</div>
<div class="B">
</div>
Upvotes: 1