给定其呈现的字符串,是否可以创建DOM对象? [英] Is there a way to create a DOM object, given its rendered string?

查看:24
本文介绍了给定其呈现的字符串,是否可以创建DOM对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以从整个字符串(不仅是innerHTML)创建DOM对象?我有一个完整的呈现DOM形式的字符串:

Is there a way to create a DOM object from the whole string, not just the innerHTML? I have a string in the form of a complete rendered DOM:

<some_tag_name class=... id=...>inner text</some_tag_name>     (1)

,并希望直接从中创建一个DOM对象.我知道有一种方法可以做到:

and want to directly create a DOM object out of it. I know that there is a way to do:

e = document.createElement("some_tag_name")
e.innerHTML = ...
e.className = ...
e.id = ...

但是,当我这样做时,我必须从我拥有的字符串(1)中提取innerhtml部分,并分析标记类型和所有属性,并将其分别分配给 e .我想简单地以(1)的形式从字符串中完成所有操作.

but when I do that, I have to extract the innerhtml part from the string (1) that I have, and analyze the tag type and all the attributes and assign that to e separately. I want to do all that simply from the string in the form of (1) that I have.

修改

我遵循了答案,但是比起初看起来要棘手.问题是,当您有一个表示 tr td 等之类的字符串时,您尝试将其作为innerHTML放入临时创建的 div,浏览器会自动在其外部添加其他标签.以下是我解决此问题的解决方法,其中 c 是字符串,而 e 是创建的元素:

I followed the answers, but it was trickier than it seemed at first. The problem is that when you have a string representing things like tr, td, etc., and you try to put that as the innerHTML to a temporarily created div, the browser automatically adds extra tags outside of it. The following is my workaround to overcome this problem, where c is the string and e is the created element:

var cTagName = c.match(new RegExp('[a-zA-Z]+'))[0].toUpperCase();
var e = document.createElement("div");
    e.innerHTML = c;
    e = e.children[0];
//// When the type of `e' does not match what `c' expects, the browser
////    automatically modifies the type of c. The following is to undo this.
if(e.tagName.toUpperCase() != cTagName){
    e = document.createElement("table");
    e.innerHTML = c;
    e = e.children[0];
};
if(e.tagName.toUpperCase() != cTagName){
    e = document.createElement("tbody");
    e.innerHTML = c;
    e = e.children[0];
};
if(e.tagName.toUpperCase() != cTagName){
    e = document.createElement("tr");
    e.innerHTML = c;
    e = e.children[0];
};

推荐答案

您可以随时这样做:

var div = document.createElement("div");
div.innerHTML = "<some> ... </some>"
var e = div.children[0];

(或者,如果您使用的是jQuery,只需 $(< some ...>")[0] ).

(or if you're using jQuery, simply $("<some ... >")[0]).

这篇关于给定其呈现的字符串,是否可以创建DOM对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆