How to create a DOM node as an object?

前端 未结 6 668
栀梦
栀梦 2020-12-07 20:04

I would like to create a DOM node, set the \'id\' attribute and then append it to \'body\'. The following seems not to work because jQuery doesn\'t see my template as an obj

6条回答
  •  有刺的猬
    2020-12-07 20:43

    Try this:

    var div = $('
    ').addClass('bar').text('bla'); var li = $('
  • ').attr('id', '1234'); li.append(div); $('body').append(li);

    Obviously, it doesn't make sense to append a li to the body directly. Basically, the trick is to construct the DOM elementr tree with $('your html here'). I suggest to use CSS modifiers (.text(), .addClass() etc) as opposed to making jquery parse raw HTML, it will make it much easier to change things later.

提交回复
热议问题