-2

私は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>
4

2 に答える 2

0

別の方法があります:

//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

于 2012-06-13T00:06:46.343 に答える
0

質問の内容、および現在存在するコメントによって、次のことを行う必要があります。

  1. Tweetsテキストを要素でラップします。具体的には<h2></h2>
  2. CSSを無効にするには、からclass属性を削除しますtd
  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);
    }  
}

注:最適化することもできますが、何が起こっているかを確認できます。また、コメントは、本番環境で削除するためのガイドとしてあります。

于 2012-06-12T23:48:27.400 に答える