▽1
●
a-kuma3 ●500ポイント ベストアンサー |
DOM には、textContent という属性があるので、それが使えると思います。
// 全ての DIV を取得 var list = document.querySelectorAll("div"); // 全ての DIV に対して実行 Array.prototype.forEach.call(list, function(div) { // DIV の中にあるテキストで、HTML を置き換える(これだけ :-) div.innerHTML = div.textContent; });
jsFiddle で試したのがこちら。「edit」ボタンを押すと、HTML を書き換えます。
https://jsfiddle.net/gc0t7bo7/
もっとベタに書くと、こんな感じになります。
function getText(node) { var e = node.firstChild; var txt = ""; do { if (e.nodeType == 3) { txt += e.nodeValue; } else if (e.nodeType == 1) { txt += getText(e); } } while (e = e.nextSibling); // == じゃないけど、間違いじゃない return txt; } // 全ての DIV を取得 var list = document.querySelectorAll("div"); // 全ての DIV に対して実行 Array.prototype.forEach.call(list, function(div) { // DIV の中にあるテキストで、HTML を置き換える div.innerHTML = getText(div); });