EdwardBlack EdwardBlack - 4 months ago 21
jQuery Question

insertAfter not working with html


  1. I have a
    p
    Element and try to wrap it inside a
    span
    .

  2. then insert it after the
    p
    tag with the id
    output
    .



I tried it like this, but the
insertAfter
is not doing it's job.



$mytext = $("p#test").html();
$myspan = "<span style='color:red'>"+$mytext+"</span";

$($myspan).insertAfter("p#output");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="test">Test</p>
<p id="output">OUTPUT:</p>





I also tried it with
append
this works:



$mytext = $("p#test");
$mytext_html = $mytext.html();

$myspan = "<span style='color:red'>"+$mytext_html+"</span";
$("p#output").append($myspan);
$mytext.remove();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="test">Test</p>
<p id="output">OUTPUT:</p>





How can i solve this?

Answer

You can rather use .wrap() to wrap an HTML structure around element in the set of matched elements.

$('p#test').wrap('<span style="color:red"></span>');

$('p#test').wrap('<span id="testspan" style="color:red"></span>');
$('#testspan').insertAfter('#output');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<p id="test">Test</p>
<p id="output">OUTPUT:</p>