You can solve, or at least avoid the problem, simply using after() instead of append() :
$("li span").last().after("<span>C</span>");
$("li span").last().after("<span>C</span>"); $('#generatedHTML').text($('li').html());
#generatedHTML { white-space: pre-wrap; font-family: mono; padding: 0.5em; margin: 0; background-color: #eee; } #generatedHTML::before { content: "Created HTML: "; color: #999; display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li> <span>A</span> </li> </ul> <div id="generatedHTML"></div>
Also, note that I adjusted your HTML: li only works with the direct child of ul or ol (it should not be contained in any other element).
Alternatively, you can use a slightly more complex alternative:
$("li").append("<span>B</span>").contents().filter(function(){ return this.nodeType === 3; }).remove();
$("li").append("<span>B</span>").contents().filter(function(){ return this.nodeType === 3; }).remove(); $('#generatedHTML').text($('li').html());
#generatedHTML { white-space: pre-wrap; font-family: mono; padding: 0.5em; margin: 0; background-color: #eee; } #generatedHTML::before { content: "Created HTML: "; color: #999; display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li> <span>A</span> </li> </ul> <div id="generatedHTML"></div>
While there was some time, I thought it was worth adding the following version of JavaScript:
let htmlToAppend = '<span>B</span>', span = document.querySelector('li span'); span.insertAdjacentHTML( 'afterend', htmlToAppend ); document.querySelector('#generatedHTML').textContent = span.parentNode.innerHTML;
let htmlToAppend = '<span>B</span>', span = document.querySelector('li span'); span.insertAdjacentHTML( 'afterend', htmlToAppend ); document.querySelector('#generatedHTML').textContent = span.parentNode.innerHTML;
#generatedHTML { white-space: pre-wrap; font-family: mono; padding: 0.5em; margin: 0; background-color: #eee; } #generatedHTML::before { content: "Created HTML: "; color: #999; display: block; }
<ul> <li> <span>A</span> </li> </ul> <div id="generatedHTML"></div>
Literature:
source share