gpt4 book ai didi

javascript - 替换特定的标签名称javascript

转载 作者:数据小太阳 更新时间:2023-10-29 05:39:57 25 4
gpt4 key购买 nike

我想知道我们是否可以更改标签中的标签名称而不是其内容。我有这个内容

< wns id="93" onclick="wish(id)">...< /wns>    

在愿望函数中我想把它改成

< lmn id="93" onclick="wish(id)">...< /lmn>

我试过这种方式

document.getElementById("99").innerHTML =document.getElementById("99").replace(/wns/g,"lmn")

但它不起作用。请注意,我只想更改具有特定 ID 的特定标签,而不是每个 wns 标签。

谢谢。

最佳答案

您不能更改现有 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);

实例: (我使用了 divp 而不是 wns 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">

参见 this gist用于可重用的功能。


旁注:我会避免使用全是数字的 id 值。尽管它们在 HTML 中有效(从 HTML5 开始),但它们在 CSS 中无效,因此您不能设置这些元素的样式,也不能使用像 jQuery 这样使用 CSS 选择器与它们交互的库。

关于javascript - 替换特定的标签名称javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15086677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com