javascript - Creating dynamic span - Stack Overflow

How can I create dynamic tags? $("<img >").attr({id: "image-1",src: "

How can I create dynamic tags?

$("<img />").attr({
    id: "image-1",
    src: "/images/flower.png",
}).appendTo("#" + imgContainer);

It will create <img src="/images/flower.png" id="image-1" />

I want to create <span> tag around <img> tag.

i.e. <span><img src="/images/flower.png" id="image-1" /></span>

How can I create dynamic tags?

$("<img />").attr({
    id: "image-1",
    src: "/images/flower.png",
}).appendTo("#" + imgContainer);

It will create <img src="/images/flower.png" id="image-1" />

I want to create <span> tag around <img> tag.

i.e. <span><img src="/images/flower.png" id="image-1" /></span>

Share Improve this question edited Oct 29, 2012 at 9:25 VisioN 146k34 gold badges287 silver badges289 bronze badges asked Oct 29, 2012 at 9:17 AsmitaAsmita 1,1903 gold badges10 silver badges31 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You can use wrap():

$("<img />").attr({
    id: "image-1",
    src: "/images/flower.png"
}).appendTo("#" + imgContainer).wrap("<span />")

You can use wrap() to wrap one element inside another. For example:

$("<img />").attr({
    id: "image-1",
    src: "/images/flower.png",
})
.appendTo("#" + imgContainer)
.wrap("<span />");

DOM operations are oh-so-expensive; just prepare the markup you're after and then append it as needed!

//Before:
$("<img />")                   //#1, create an element outside of the tree
.attr({                        //#2? change its attributes
  id: "image-1",
  src: "/images/flower.png"
})
.appendTo("#" + imgContainer)  //#3, add the element to DOM
.wrap("<span />");             //#4, create and add another element to DOM

//After:
$('<span><img src="/images/flower.png" id="image-1"></span>')  //#1
.appendTo("#" + imgContainer);                                 //#2

Here is a jsperf test case which results in ~5K ops/sec for the first case and ~14K for the latter (on my pretty decent box).

This is not premature optimization, either. If you have, for instance, ajax-populated 7x10 table and you create every cell individually... and wrap them into <tr> elements... and then add it to a table, the overhead adds up. Operate on a string and your script will be at least 80 times faster!

Another aspect to remember is that jsperf explicitly measures javascript performance only. If you're manipulating a table, its content will be even more aggressively re-painted/re-flown.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745288276a4620697.html

相关推荐

  • javascript - Creating dynamic span - Stack Overflow

    How can I create dynamic tags? $("<img >").attr({id: "image-1",src: "

    5小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信