开发者

jQuery creating and modifying elements

开发者 https://www.devze.com 2023-04-11 05:15 出处:网络
I\'m using an HTML snippet to insert some text into the element, then display it somewhere: var elemTemp = $(\'<span /><strong class=\"value unit\" />\').find(\'span\').text(\'hi!\').end(

I'm using an HTML snippet to insert some text into the element, then display it somewhere:

var elemTemp = $('<span /><strong class="value unit" />').find('span').text('hi!').end();
elemTemp.appendTo('#someDiv');

I want to insert "开发者_如何转开发hi" inside the span but could not get it working. The find() method doesn't seem to find the span.


find looks down the DOM tree, but your span is not a descendant, so find won't find it. Use siblings instead:

var elemTemp = $('<span /><strong class="value unit" />').siblings('span').text('hi!').end();

Here's a working example. Note that this produces HTML along the lines of:

<span>hi!</span>
<strong class="value unit"></strong>

I'm not sure if you were aiming for that, or if you wanted the strong to be a child of the span.


Why not do this as simply and quickly as possible?

 $('#someDiv').append('<span>hi!</span>'); // or whatever HTML you want in there


You have to specify which span-tag you want to insert "hi" into. The easiest way is to set a class on the span-tag.

HTML:

<span class="hello"></span>

jQuery:

$('span.hello').html('hi');
0

精彩评论

暂无评论...
验证码 换一张
取 消