简体   繁体   中英

How can I close an element created by document.createElement?

If I write this:

document.createElement("img")

The generated html is: <img> , and I can add attributes on this element. However, is there a parameter or something I could pass to createElement to make it self-closing? Or is there a dom function I could call to generate the </a> closing tag?

It doesn't matter if tags are self-closing or not when they've been processed by the DOM. If you type <img/> in the source and then look at innerHTML , you'll see <img> instead.

Similarly, you don't need to "generate" the closing tag because it's already there. The browser has already taken your text-based HTML and turned it into a tree of nodes. Using DOM functions affects the tree, and getting innerHTML just turns it into one of many possible text formats that produce the same tree.

It happens automatically when you append the element somewhere.

Like this:

 var newElem = document.createElement ("div");
 newElem.innerHTML = "sample text";
 newElem.style.color = "red";

 var container = document.getElementById ("container");
 container.appendChild (newElem);
 //the container contains a closing div tag

See the fiddle: http://jsfiddle.net/jakHt/

The DOM structure has no real notions of tags as HTML markup. All that data has been deserialised and turned into a structure.

Once you append it to body(DOM), browser will automatically closes it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM