如何使用JavaScript替换html元素
How do I replace html elements using JavaScript?
我今天花了大约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>';
}
相关文章:
- 如何设置html元素填充的动画
- 删除对HTML元素的拖动
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 如何使用JQuery在Javascript中转换字符串中的HTML元素
- 一个html元素的克隆次数太多
- 使用AngularJS Directive WHITOUT$scope创建一个动态html元素
- 为什么我在Internet Explorer上看不到html元素
- 重新排列HTML元素的顺序并更改内容
- 使用.on动态添加jquery/js不知道的html元素
- 如果类不是一个选项,如何在使用 jQuery 时控制(避免)嵌套 html 元素的样式
- 如何将html元素添加到tampermonkey中
- 访问html元素值javascript
- 如何在HTML元素上创建函数,而不是将元素作为参数传递
- 自定义HTML元素属性未显示-Web组件
- 让HTML元素充当停止滚动的锚点
- 将html元素插入到文本字符串中,以匹配另一个html字符串
- 替换HTML元素中的字符
- 如何将html元素添加为生成的内容
- 如何使用JavaScript在没有html dom的情况下隐藏html元素
- 使用JS加载HTML元素