使用 javascript 替换 HTML 值

Replace HTML values using javascript

本文关键字:HTML 替换 javascript 使用      更新时间:2023-09-26

我在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>

根据问题内容和当前存在的注释,您需要:

  1. 用元素换行文本Tweets,特别是<h2></h2>
  2. td中删除 class 属性以禁用 CSS
  3. 使用纯 JavaScript
  4. 假设存在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