简体   繁体   English

Javascript DOM文档来自标记源的createElement

[英]Javascript DOM Document createElement from tag source

Is there a way to create a new element in a Document object from the tag source? 有没有办法从标记源创建Document对象中的新元素? Essentially what I'd like to do is something to effect of: 基本上我想要做的是:

myDocument.createElement('<sometag attr="lol">');

No, native DOM API for .createElement doesn't support that syntax. 不, .createElement原生DOM API不支持该语法。 You need to create the plain Element and set any property either directly on the object 您需要创建plain元素并直接在对象上设置任何属性

newElem.attr = "lol";

or (better), use .setAttribute() 或(更好),使用.setAttribute()

newElem.setAttribute( 'attr', 'lol' );

What you "could" do is do create a documentFragment , then use .innerHTML to write that string into that fragment and finally .append its contents to its target destination. 你“可能”做的是什么创造 documentFragment ,然后使用 .innerHTML编写串到该片段终于 .append其内容到其目标。

well, use innerHTML instead of trying to hack dom manipulation for this kind of thing. 好吧,使用innerHTML而不是试图破解dom操作这种事情。

To do so, create a valid node with dom if you want (or get it via getElementById), then set innerHTML of this node with your code 为此,如果需要(或通过getElementById获取),请使用dom创建一个有效节点,然后使用您的代码设置此节点的innerHTML

The innerHTML property works here - but it's a tad bit difficult to place the thing where you want it sometimes. innerHTML属性在这里工作 - 但有时候把它放在你想要的东西上有点困难。 For example: 例如:

var div = document.createElement('div');
div.innerHTML = "<img src='http://www.google.com/logos/classicplus.png'/>";

In my humble opinion, it's a heck of a lot easier to use jQuery to handle it for you, as it comes with all of the jQuery methods already attached. 在我看来,使用jQuery为你处理它更容易,因为它附带了所有已经附加的jQuery方法。

var div = $("<div class='blah'><img src='http://www.google.com/logos/classicplus.png'/></div>");
div.find('img').hide();
div.appendTo('body');
div.find('img').fadeIn();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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