使用 javascript 替换 HTML 值
Replace HTML values using javascript
我在HTML中有以下代码,并希望使用javascript替换它们
原始代码
<td class="tabButton dijitHidden tweetsTabButton selectedTab" dojoattachpoint="tweetsTabButton" data-type="twitter" style="display: none;">
Tweets
<div class="arrow-up"><div class="arrow-up-content"></div></div>
</td>
将其替换为
<td dojoattachpoint="tweetsTabButton" data-type="twitter" style="display: none;">
<h2>Tweets</h2>
</td>
根据问题内容和当前存在的注释,您需要:
- 用元素换行文本
Tweets
,特别是<h2></h2>
- 从
td
中删除class
属性以禁用 CSS - 使用纯 JavaScript
- 假设存在
table
ID
并使用data-type
属性作为验证!
请参阅此工作小提琴示例!
JavaScript
// get the table by ID
var table = document.getElementById("table-id");
// get the table cells
var cells = table.getElementsByTagName("td");
// for each table cell found
for (var i = 0; i < cells.length; i++) {
// get the attribute 'data-type'
var status = cells[i].getAttribute("data-type");
// if 'data-type' contains the value 'twitter'
if ( status == "twitter" ) {
// create the 'h2' element
var h2 = document.createElement("h2");
// append a textnode to the created element with the text 'Tweets'
h2.appendChild(document.createTextNode('Tweets'));
// remove the current text 'Tweets'
cells[i].removeChild(cells[i].firstChild);
// remove the class atrribute
cells[i].removeAttribute('class');
// append the new element to the current 'td'
cells[i].appendChild(h2);
}
}
注意:可以优化,但您可以看到发生了什么。此外,注释可以指导您完成,在生产中删除。
这是另一种方法:
//index [0] assumes you want to modify the first td matching this set of class rules..
var td = document.getElementsByClassName("tabButton dijitHidden tweetsTabButton selectedTab")[0];
//remove the attributes, as requested
td.removeAttribute('class');
td.removeAttribute('dojoattachpoint');
//sets the innerHTML of the element, overwriting the original one
td.innerHTML = '<h2>Tweets</h2>';
请注意,td
仍然具有使其不可见的display:none
,您可以添加:
td.style.display = "table-cell";
使其动态可见。不要忘记在 DOM 准备就绪/加载后运行脚本。
JSFiddle
相关文章:
- 用JavaScript替换Android WebView模板上的html文本
- 用任意html替换ExtJS组件的内容
- 如何用一些已编译的HTML替换元素的值
- 使用 Javascript 将 html 替换为 html
- 将HTML替换为Mobile Design中的图像.比如Paypal.com
- 我可以用JS或HTML替换屏幕吗?
- 如何使用 JS 将 HTML 替换为另一个 HTML 块
- 用带有javascript的新HTML替换HTML
- SVG/XML中是否有一些内部HTML替换
- Javascript Slider标题将html替换为只处理第一项的标题
- 用格式化的html替换句子中的单词
- javascript用多个html替换()多个bbcode实例
- 用字符串中包含的一些HTML替换HTML元素
- 在Google Apps Script中用HTML替换文本
- 简单的Javascript HTML替换
- 如何通过jquery/javascript将我的旧html替换为新html
- 如何在contenteditable元素中用html替换所选文本
- 循环遍历元素数组,将html替换为data
- 如何用页面上的另一段HTML替换一段HTML
- 用内联html替换字符串