javascript - 如何获取它们之间没有文本的第一个子元素

标签 javascript jquery

我正在使用名为 KindEditor 的所见即所得编辑器。我发现有时候它会额外添加一个<br>自动地。我想知道如何删除多余的<br>使用 jQuery。

例如,在下面的代码块中,我想删除第一个 <br>放在代码块A和代码块B中,并保留在代码块C中。

代码块A

<p>
  <br> <!-- it's useless now; need to remove -->
  Taiwan next
  <br>
  Taichung goes global!
</p>

代码块B

<p>

  <br> <!-- it's also useless now because the text before it's empty; need to remove -->
  Taiwan next
  <br>
  Taichung goes global!
</p>

代码块C

<p>
  New Taipei City
  <br> <!-- The content before it is not empty, so it's useful; can not be removed -->
  Taiwan next
  <br>
  Taichung goes global!
</p>

我想使用jQuery来做到这一点,我写了一个如下的选择:

$("p > br:first-child")

但它也会删除 <br>在代码块 C 中,那么如何使用 jQuery 选择器来做到这一点?

虽然我们可以使用正则表达式来完成,但我想在 jQuery 中完成。

最佳答案

您可以使用filter来检查前一个节点是否为空。

//console.log($("p > br:first-child"))

$('p > br:first-child').filter(function(){
    return this.previousSibling.wholeText.trim() == "";
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<p>
  <br> <!-- it's useless now,need to remove -->
  Taiwan next
  <br>
  Taichung goes global!
</p>


<p>

  <br> <!-- it's also useless now due to the text before it's empty,need to remove -->
  Taiwan next
  <br>
  Taichung goes global!
</p>


<p>
  New Taipei City
  <br> <!-- The content before it is not empty,so it's useful,can not be removed -->
  Taiwan next
  <br>
  Taichung goes global!
</p>

关于javascript - 如何获取它们之间没有文本的第一个子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49809036/

相关文章:

javascript - 将选择标签替换为复选框以在深色和浅色主题之间切换

javascript - Coffeescript 相当于 On Document Ready

javascript - 继续检查 Div 是否包含特定文本

java - 将 .js.map 文件添加到 apache wicket-6.x 中的页面标题

javascript - 如何在 React JS 和 webpack 中使用 moment.js 格式化时间

javascript - 在您的 Google Map API V3 请求中将 clientId 和签名放在哪里?

javascript - 在 javascript 中呈现 HTML 时包含外部 CSS

java - 使用 Java 解析 javascript 生成的内容

php - 检测禁用 JavaScript 的浏览器并为它们分离站点?

javascript - 我正在使用 jquery/ajax 进行登录。发送作品和服务器端返回登录,但这失败了