How to create a DOM node as an object?

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

    There are three reasons why your example fails.

    1. The original 'template' variable is not a jQuery/DOM object and cannot be parsed, it is a string. Make it a jQuery object by wrapping it in $(), such as: template = $(template)

    2. Once the 'template' variable is a jQuery object you need to realize that

    3. is the root object. Therefore you cannot search for the LI root node and get any results. Simply apply the ID to the jQuery object.

    4. When you assign an ID to an HTML element it cannot begin with a number character with any HTML version before HTML5. It must begin with an alphabetic character. With HTML5 this can be any non-whitespace character. For details refer to: What are valid values for the id attribute in HTML?

    PS: A final issue with the sample code is an LI cannot be applied to the BODY. According to HTML requirements it must always be contained within a list, i.e. UL or OL.

提交回复
热议问题