Clearest way to build html elements in jQuery

前端 未结 10 1177
一个人的身影
一个人的身影 2020-12-12 11:12

I\'ve seen a lot of different styles (and few different methods) of creating elements in jQuery. I was curious about the clearest way to build them, and als

10条回答
  •  爱一瞬间的悲伤
    2020-12-12 12:02

    When it comes to DOM building I try to avoid string concatenations as they might lead to subtle bugs and non properly encoded output.

    I like this one:

    $('
    ', { html: $('

    ', { html: title }).after( $('
    ', { 'text': content, 'class': 'content' }) ) }).appendTo('body');

    generates:

        ...
        

    some title

    some content

    and it ensures proper HTML encoding and DOM tree building with matching opening and closing tags.

提交回复
热议问题