2

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>
1
  • Just use $("<span class='wf_captionfirst'>adsfasdff</span>").insertAfter("img"); Commented Mar 18, 2020 at 13:17

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

6 Comments

I am moving the caption from one place to another so if i use insertafter it gets dulicated on another place
I don't understand what you mean by duplicate. I updated the answer with a demo, it doesn't duplicate it.
ACtually i m using insertafter but the element remain on that place and insert after works also. Both are showing
@jack Include your full HTML. We don't know where .wf_captionfirst is located.
<div id="articlespace"> <img src="img/testw.jpg"></div> <p><span class="wf_caption" style="margin-left: 9px; float: right; margin-bottom: 9px; max-width: 400px; display: inherit;"><img src="/images/asdfasdf-asdfasdf.jpg">asdfasdfasfdasdf</span></p>
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.