既存のDOM要素のタグ名を変更することはできません。代わりに、置換を作成してから、要素があった場所に挿入する必要があります。
これの基本は、子ノードを置換に移動し、同様に属性をコピーすることです。たとえば、次のようになります。
var wns = document.getElementById("93");
var lmn = document.createElement("lmn");
var index;
// Copy the children
while (wns.firstChild) {
lmn.appendChild(wns.firstChild); // *Moves* the child
}
// Copy the attributes
for (index = wns.attributes.length - 1; index >= 0; --index) {
lmn.attributes.setNamedItem(wns.attributes[index].cloneNode());
}
// Replace it
wns.parentNode.replaceChild(lmn, wns);
実例:( 私はdiv
andp
ではなくwns
andを使用lmn
し、変更を確認できるように境界線のあるスタイルシートを使用してスタイルを設定しました)
document.getElementById("theSpan").addEventListener("click", function() {
alert("Span clicked");
}, false);
document.getElementById("theButton").addEventListener("click", function() {
var wns = document.getElementById("target");
var lmn = document.createElement("p");
var index;
// Copy the children
while (wns.firstChild) {
lmn.appendChild(wns.firstChild); // *Moves* the child
}
// Copy the attributes
for (index = wns.attributes.length - 1; index >= 0; --index) {
lmn.attributes.setNamedItem(wns.attributes[index].cloneNode());
}
// Insert it
wns.parentNode.replaceChild(lmn, wns);
}, false);
div {
border: 1px solid green;
}
p {
border: 1px solid blue;
}
<div id="target" foo="bar" onclick="alert('hi there')">
Content before
<span id="theSpan">span in the middle</span>
Content after
</div>
<input type="button" id="theButton" value="Click Me">
再利用可能な関数については、この要点を参照してください。
補足:id
すべて数字の値は使用しないようにします。これらはHTMLでは有効ですが(HTML5以降)、CSSでは無効であるため、これらの要素のスタイルを設定したり、CSSセレクターを使用して要素と対話するjQueryなどのライブラリを使用したりすることはできません。