[英]How do you get an element by ID from an external HTML document using Javascript?
I want to have a list of pre-made elements in a seperate HTML doc that I can add to my HTML page. 我想要一个单独的HTML文档中的预制元素列表,可以将其添加到HTML页面中。 I know I can create elements and then add them like so:
我知道我可以创建元素,然后像这样添加它们:
document.body.appendChild(document.createElement("div"));
But the child I want to append is an HTML element in another HTML document. 但是我要附加的子元素是另一个HTML文档中的HTML元素。 So something like this:
所以像这样:
<html>
<!-- External doc -->
<div id="ext">
</div>
</html>
I want to add the div
to the main document like this: 我想像这样将
div
添加到主文档中:
<html> <--Main document-->
<head></head>
<body></body>
<script>
document.body.appendChild("externalDocument".getElementById("ext"));
</script>
</html>
How can I reference the external document and get the div
? 如何引用外部文档并获取
div
?
Maybe you can add loaclstorage div element it.Then you can call that lcoalstorage and use it 也许您可以添加loaclstorage div元素,然后可以调用该lcoalstorage并使用它
<html>
<body>
<!-- External doc -->
<div id="ext">
</div>
<script>
var div_element = document.getElementById("ext");
localStorage.element = Json.Stringfy(div_element);
</script>
</body>
</html>
then json.parse it and use like this 然后json.parse它并像这样使用
<html> <--Main document-->
<head></head>
<body></body>
<script>
var element = Json.Parse(localStorage.element);
document.body.appendChild(element);
</script>
It's not clear how do you get this external HTML. 目前尚不清楚如何获取此外部HTML。 So, I thought about the following:
因此,我想到了以下几点:
var htmlString = '<html><div id="div1">content</div></html>';
var html = (new window.DOMParser()).parseFromString(htmlString, "text/html");
html.getElementById("div1").innerHTML; // content
If you want to use the pre-created HTML component then please go with template engines. 如果您想使用预先创建的HTML组件,请使用模板引擎。 There are mainly popular template engine available visit : https://www.creativebloq.com/web-design/templating-engines-9134396
主要有流行的模板引擎可以访问: https : //www.creativebloq.com/web-design/templating-engines-9134396
They provide many other feature also such as make dynamic templates, supports loops, variable, json, conditions and much more ... 它们还提供许多其他功能,例如制作动态模板,支持循环,变量,json,条件等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.