How to create a DOM node as an object?

前端 未结 6 705
栀梦
栀梦 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:56

    First make your template into a jQuery object:

     var template = $("
  • bla
  • ");

    Then set the attributes and append it to the DOM.

     template.find('li').attr('id','1234');
     $(document.body).append(template);
    

    Note that it however makes no sense at all to add a li directly to the DOM since li should always be children of ul or ol. Also it is better to not make jQuery parse raw HTML. Instead create a li, set its attributes. Create a div and set it's attributes. Insert the div into the li and then append the li to the DOM.

提交回复
热议问题