通过ID从字符串中提取元素? [英] Extract element by ID from string?
问题描述
我有一个包含以下文本的字符串:
I have a string which contains this text:
<!DOCTYPE html>
<html>
<head>
<title>ExtractDiv test</title>
</head>
<body>
<p>Apples and oranges</p>
<div id="main">
<ul style="list-style-type: upper-roman">
<li>Äpfel</li>
<li>Birnen</li>
</ul>
</div>
<p>Men and women</p>
</body>
</html>
现在,我需要一个JavaScript函数,该函数可以从文本中返回具有特定ID 作为字符串的DOM元素,例如:
Now I need a JavaScript function which gives me back a DOM element with a specific ID as a string from this text, for example:
function ExtractElementByIdFromString(HTMLString, IdString)
{
var ExtractedElement = ???(HTMLString, IdString);
return ExtractedElement;
}
因此在这种情况下,此函数的结果将是:
So the RESULT of this function in this case would be:
<div id="main">
<ul style="list-style-type: upper-roman">
<li>Äpfel</li>
<li>Birnen</li>
</ul>
</div>
这可能吗?
推荐答案
您可以使用本地 DOMParser :
var str = "<!DOCTYPE……………" // your HTML string
var doc = new DOMParser().parseFromString(str, "text/html")
然后只使用常规的DOM方法:
Then just use regular DOM methods:
console.log( doc.getElementById("main") )
请注意,使用DOMParser比将字符串插入文档的innerHTML中的某个位置更有效,更安全,因为只会创建结构-< script>
元素将不会执行,图像将不会被加载,CSS将不会尝试对其进行应用,也不会进行渲染等.
Note that using a DOMParser is more efficient and safer than inserting the string somewhere in your document's innerHTML, because only the structure will be created — <script>
elements won't be executed, images won't be loaded, CSS will no try to apply to it, no rendering will occur, etc.
这篇关于通过ID从字符串中提取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!