英文:
How can I append a `div` in a HTML to another HTML's body?
问题
You can append the content from part.html
to main.html
using JavaScript like this:
// Assuming you have loaded the content of 'part.html' and 'main.html' into variables, for example:
var partContent = '<div id="GBVX1WkdGsQT1b36AbVC" class="plotly-graph-div" style="height:100%; width:100%;"></div>';
var mainContent = '<!doctype html><html><head></head><body></body></html>';
// Create a temporary element to hold the 'part.html' content
var tempElement = document.createElement('div');
tempElement.innerHTML = partContent;
// Append the 'div' from 'part.html' to the 'body' of 'main.html'
document.body.appendChild(tempElement.querySelector('div'));
// Now 'main.html' has the 'div' from 'part.html' appended to its body
This JavaScript code extracts the div
element from part.html
and appends it to the body
of main.html
.
英文:
I have the following part.html
file, which contains a div
and script
:
<div id="GBVX1WkdGsQT1b36AbVC" class="plotly-graph-div" style="height:100%; width:100%;"></div>
<script type="text/javascript">
Plotly.newPlot("GBVX1WkdGsQT1b36AbVC", {
"data": [],
"layout": {},
"config": {}
});
</script>
And I have a main.html
, which is the file I am rendering on the web page:
<!doctype html>
<html>
<head>
</head>
<body>
</body>
</html>
How can I append the content from part.html
to main.html
with using Javascript
?
答案1
得分: 2
你可以使用 fetch()
来获取 part.html
中的文本,然后将 document.body.innerHTML
设置为该文本。像这样:
main.html
<!doctype html>
<html>
<head>
<script>
fetch('part.html') // 这可以是任何HTML文件的URL
.then(res => res.text())
.then(text => document.body.innerHTML = text);
</script>
</head>
<body>
</body>
</html>
part.html
<!-- 仅供演示目的,可以是任何内容 -->
<h1>测试</h1>
这也可以很容易地适应使用多个部分,只需进行多个 fetch()
调用,并在每次调用中执行 document.body.innerHTML += text
。
英文:
You can use fetch()
to get the text of part.html
, then set document.body.innerHTML
to that text. Like this:
main.html
<!doctype html>
<html>
<head>
<script>
fetch('part.html') // this can be the URL of any HTML file
.then(res => res.text())
.then(text => document.body.innerHTML = text);
</script>
</head>
<body>
</body>
</html>
part.html
<!-- Just for demo purposes, can be anything -->
<h1>Test</h1>
This can also be easily adapted to use multiple parts by making multiple fetch()
calls and just doing document.body.innerHTML += text
each time instead.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论