javascript - insertAfter not working with html -


  1. i have p element , try wrap inside span.
  2. then insert after p tag id output.

i tried this, insertafter 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 tried append 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 solve this?

you can rather use .wrap() wrap html structure around element in 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>


Comments