如何使用JavaScript替换html元素

How do I replace html elements using JavaScript?

本文关键字:html 元素 替换 JavaScript 何使用      更新时间:2024-01-16

我今天花了大约3个小时试图用JavaScript替换页面上的html元素。

我尝试了很多事情,但都没有取得多大成功。例如,如果我想用代码片段2替换代码片段1,该怎么做?

我试过

document.getElementById('wide-left').innerHTML="(code snippet 1)";

但它只是抛出了一个错误。

对不起,如果我解释得不够清楚,我已经尽力了。如有任何帮助,我们将不胜感激。

代码片段1

<h4 id="select-head">Select</h4>
<h4 id="summary-head">Summary</h4>
</div>

代码片段2

<div class="col9 single-product" id="wide-left">
    <div class="product-name hidden-lg">
        <h2><span>Reebok Ventilator x Mita</span> <em class="stockcode"><span>M48281</span></em></h2>
    </div>
  <!-- end of .product-name -->
  <div class="row unexpanded" id="product-info">
      <div class="col4 product-pic-width">

我将在这里尝试说明使用代码片段工具修改HTML的基本原理:

var snip1 = document.getElementById("snip1"),
  snip2 = document.getElementById("snip2");
setTimeout(function() {
  snip1.innerHTML = snip2.innerHTML;
}, 1000); // This code copies the HTML from within snip2 to snip1.
setTimeout(function() {
  snip2.innerHTML = "";
}, 2000); // This code clears snip2.
setTimeout(function() {
  snip1.getElementsByTagName("span")[0].style.color = "blue";
}, 3000); // This code changes the CSS for <span> within snip1.
setTimeout(function() {
  snip2.textContent = snip1.innerHTML
}, 4000); // This code copies the HTML from snip1 as text into snip2.
<div>
  Here is some <span id="snip1"></span> content!
</div>
<div>
  Here is some <span id="snip2"><span style="color:red">more</span></span>content!
</div>

加载文档对象模型("DOM")后,请尝试编辑元素,否则会遇到错误。

document.onload = function()
{
    document.getElementById('wide-left').innerHTML = '<p>This is some HTML</p>';
}