将结束</a>标记移动到包含元素的末尾

Pix*_*yle 17 javascript jquery

我正在尝试获取一个环绕div中所有文本的链接.我只能找到完全移动某些DOM元素的解决方案,或者将其他元素移动到元素中.

现在的情况:

<div class="text">
    <a href="link">text</a> and more text
</div>
Run Code Online (Sandbox Code Playgroud)

理想情况:

<div class="text">
    <a href="link">text and more text</a>
</div>
Run Code Online (Sandbox Code Playgroud)

不幸的是,我无法更改标记,因此我必须使用jQuery做一些事情.

dfs*_*fsq 11

避免直接搞乱html,最好不要更改或覆盖.您需要做的就是采用下一个文本同级节点并附加到上一个a:

$('.text a').each(function() {
  $(this).append(this.nextSibling)
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="text">
  <a href="link">text</a> and more text
</div>
Run Code Online (Sandbox Code Playgroud)

如果需要,可以检查下一个节点是否为TextNode,如果需要跳过元素节点:

if (this.nextSibling.nodeType === 3) {
  $(this).append(this.nextSibling)
}
Run Code Online (Sandbox Code Playgroud)


Moh*_*mad 9

您需要使用.append( function )插入nextSibling锚进去.

$(".text a").append(function(){
  return this.nextSibling
});
Run Code Online (Sandbox Code Playgroud)

$(".text a").append(function(){
  return this.nextSibling
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text">
  <a href="link">text</a> and more text
</div>
Run Code Online (Sandbox Code Playgroud)

您也可以使用.html( function ),然后使用删除下一个兄弟.remove()

$(".text a").html(function(i, h){
  return h + this.nextSibling.nodeValue;
})[0].nextSibling.remove();
Run Code Online (Sandbox Code Playgroud)

或者使用ES6在一行中

$(".text a").html((i,h) => h+this.nextSibling.nodeValue)[0].nextSibling.remove();
Run Code Online (Sandbox Code Playgroud)

$(".text a").html(function(i, h){
  return h + this.nextSibling.nodeValue;
})[0].nextSibling.remove();
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text">
  <a href="link">text</a> and more text
</div>
Run Code Online (Sandbox Code Playgroud)


或使用纯JavaScript

var ele = document.querySelector(".text a");
ele.innerHTML += ele.nextSibling.nodeValue;
ele.nextSibling.remove();
Run Code Online (Sandbox Code Playgroud)

var ele = document.querySelector(".text a");
ele.innerHTML += ele.nextSibling.nodeValue;
ele.nextSibling.remove();
Run Code Online (Sandbox Code Playgroud)
<div class="text">
  <a href="link">text</a> and more text
</div>
Run Code Online (Sandbox Code Playgroud)

  • @PeterB由于逗号运算符,他正在返回"h + text".但你正确地将两行代码粉碎成一个使用逗号并不是一个好的风格. (3认同)