将父元素替换为其内容
Replace parent element with its contents
我正在尝试做与这个问题类似/相同的事情:如何在JavaScript中只删除父元素而不删除其子元素?
<div>
This is some text here
<h2>This is more text</h2>
</div>
我只想去掉H2标签。结果应该是:
<div>
This is some text here
This is more text
</div>
假设我已经有H2元素:
if (parentElement.nodeName.toLowerCase() == "h2") {
//now what? I basically want to this: $.replaceWith(parentElement.innerText)
//just without jQuery
}
使用现代JS
const h2 = document.querySelector('h2');
h2.replaceWith(h2.firstChild);
要替换为所有子项,请使用:
h2.replaceWith(...h2.childNodes); // or h2.children, if you don't want textNodes
developer.mozilla.org
我可以使用-96%Oct'22
假设变量h2
准确地引用了您想要操作的h2
元素,我的第一个想法是:
var h2 = document.getElementsByTagName('h2')[0],
textnode = h2.firstChild;
h2.parentNode.insertBefore(textnode,h2.nextSibling);
h2.parentNode.removeChild(h2);
JS Fiddle演示。
为了使其更干燥,一种函数方法可以是:
function unwrapH2(el) {
if (!el) {
return false;
}
else {
var textnode = el.firstChild,
elParent = el.parentNode;
elParent.insertBefore(textnode, h2.nextSibling);
elParent.removeChild(h2);
}
}
var h2 = document.getElementsByTagName('h2')[0];
unwrapH2(h2);
JS Fiddle演示。
根据Felix Kling的评论(如下)对上述内容进行了调整,并使用了replaceChild()
:
function unwrapH2(el) {
if (!el) {
return false;
}
else {
var textnode = el.firstChild,
elParent = el.parentNode;
elParent.replaceChild(textnode,el);
}
}
var h2 = document.getElementsByTagName('h2')[0];
unwrapH2(h2);
JS Fiddle演示。
首先,开始使用jQuery。它让你的生活更轻松。
在jQuery中,执行以下操作:
var h2html = $('div h2').html();
$('div h2').remove();
$('div').append(h2html);
编辑:
以上仅适用于1个div
和1个h2
元素,这是div中的最后一个元素。这只是一个快速示例。以下是让你的生活更加轻松的代码:
$('div h2').each(function (x, y) {
$(this).replaceWith($(this).html());
});
相关文章:
- jQuery appendTo 替换元素而不是添加元素,如果正在添加的元素预先存在于列表中
- 如何用一些已编译的HTML替换元素的值
- 如何替换元素属性中的部分文本
- 替换
元素中的特殊字符的问题
- 为什么这个脚本只工作一次?只替换元素一次,然后再也不替换
- JS如何在加载页面之前替换元素(awesomium c#)
- Javascript.替换元素“<termref/>"用规则的“;文本”;
- 替换元素中字符串的所有位置
- regex替换元素文本
- 在Javascript中,如何用变量替换元素的名称
- 如何实现 Angular 指令来替换元素,但仅限于某些情况
- 事件调用在 ajax 替换元素后多次
- 替换元素后,无法单击该元素
- jQuery查找并替换元素中的关键字
- 如何在 JavaScript 中用 DOM 操作函数替换元素内容
- .each(从html元素生成下拉列表,替换元素)
- 替换元素中的类名,但不删除此元素中的其他类纯javascript
- Javascript push()替换元素,而不是追加
- 如何替换元素标记,然后将其添加到现有元素
- 查找并替换元素's类使用jQuery