How do I append both an element and text to a div

2019-08-17 12:51发布

问题:

I'm using jQuery and trying to append both an element and some text to an existing div element. However, when I try this

$('<img src="/img.png" />').appendTo(gMenuItemInnerDiv);
$(gMenuItemInnerDiv).text(name);

The img element from the first line is wiped out. How can I get both things into my div?

回答1:

var gMenuItemInnerDiv = $('#something');
var name = "<b>Yay</b>";

$('<img src="/img.png" />').appendTo(gMenuItemInnerDiv);
gMenuItemInnerDiv.append( document.createTextNode(name) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="something"></div>



回答2:

Did you try something like this ?

$('<img src="/img.png" />').appendTo(gMenuItemInnerDiv);
$('<span>' + name +'</span>').appendTo(gMenuItemInnerDiv);

:)