是否可以将DOM元素转换为字符串并返回?

问题描述 投票:2回答:1

我正在获取任何DOM元素(例如document.body,我想将其转换为String,如下所示:

function convert(el){
//should return a String
}

alert(convert(document.body));
//should alert (String) "document.body"
alert(document.getElementById('foo'));
//should alert (String) "document.getElementById('foo')"

我还想将那些字符串转换回(如果可能的话,不使用eval())。例如:

function convertBack(el){
//should return a node
}

convertBack('document.body').innerHTML = 'foo';
//should change the innerHTML of document.body to foo

对于某些人来说,这似乎没有用,但这是我针对目标元素的一种变通方法,目前尚不存在。我没有使用任何图书馆。

谢谢!

javascript string function dom elements
1个回答
1
投票

使用标准JavaScript,并以e作为元素:

转换为字符串:

const html = e.outerHTML

转换回元素:

const temp = document.createElement('div') // Can be any element
temp.innerHTML = html
const e = temp.children[0]

使用jQuery,这很容易,尽管我一般不鼓励使用它。

转换为字符串:

var s = e.outerHTML;

转换回元素:

var e = $(s)[0];

$("<div></div>")解析HTML并返回jQuery对象。您可以通过[0]

获得对第一个元素的引用
© www.soinside.com 2019 - 2024. All rights reserved.