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

Ood*_*Ood 7 javascript string dom element function

我正在获取任何 DOM 元素(例如 document.body),并且我想将其转换为字符串,如下所示:

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')"
Run Code Online (Sandbox Code Playgroud)

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

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

convertBack('document.body').innerHTML = 'foo';
//should change the innerHTML of document.body to foo
Run Code Online (Sandbox Code Playgroud)

这对你们中的一些人来说可能看起来毫无用处,但这是我针对尚不存在的目标元素的解决方法。我没有使用任何库。

谢谢!

wiz*_*lus 4

使用标准 JavaScript,e元素:

转换为字符串:

const html = e.outerHTML
Run Code Online (Sandbox Code Playgroud)

转换回元素:

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

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

转换为字符串:

var s = e.outerHTML;
Run Code Online (Sandbox Code Playgroud)

转换回元素:

var e = $(s)[0];
Run Code Online (Sandbox Code Playgroud)

$("<div></div>")解析 HTML 并返回一个 jQuery 对象。您可以使用以下命令获取对第一个元素的引用[0]