javascript - 使用 jquery 删除两个跨度之间的内容

标签 javascript jquery html css

这是我的 HTML 代码

<div class="breadcrumbs">
    <span typeof="v:Breadcrumb">
    <a title="Go to Innomations." href="" class="home">Home</a></span>
    >>
    <span typeof="v:Breadcrumb" class="turnoffmain">
    <a rel="v:url" property="v:title" title="Go to Products." href="">Products</a></span> 
</div>

我想删除两个 span 之间的内容 >>

我该怎么做?

我试过这样

$("a").each(function(){
   if($(this).attr("title") == "Go to Products."){
      $(this).closest('span').addClass('turnoffmain');
    } 

即,迭代到 href 并确定 “Go to Products.” 并添加一个类 turnoffmain,它将隐藏第二个跨度。

但是我怎样才能删除这两个跨度之间的 >>> 呢?

最佳答案

你可以在 contents()each() 的帮助下做这样的事情

$('.breadcrumbs').contents().each(function() {
  if (this.nodeType == 3)
    this.remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="breadcrumbs">
  <span typeof="v:Breadcrumb">
    <a title="Go to Innomations." href="" class="home">Home</a></span>
  >>
  <span typeof="v:Breadcrumb" class="turnoffmain">
    <a rel="v:url" property="v:title" title="Go to Products." href="">Products</a></span> 
</div>
或者更具体地删除 span 标记之间的元素

$('.breadcrumbs').contents().each(function() {
  console.log(this.nextSibling.nodeName == 'SPAN');

  if (this.nodeType == 3 && this.nextSibling && this.prevSibling && this.nextSibling.nodeName == 'SPAN' && this.prevSibling.nodeName == 'SPAN')
    this.remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="breadcrumbs">
  <span typeof="v:Breadcrumb">
    <a title="Go to Innomations." href="" class="home">Home</a></span>
  >>
  <span typeof="v:Breadcrumb" class="turnoffmain">
    <a rel="v:url" property="v:title" title="Go to Products." href="">Products</a></span> 
</div>

或者如您所说,如果内容位于 turnoffmain 类之上,则将其删除

$('.breadcrumbs').contents().each(function() {
  console.log(this.nextSibling.nodeName == 'SPAN');

  if (this.nodeType == 3 && $(this.nextSibling).is('.turnoffmain'))
    this.remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="breadcrumbs">
  <span typeof="v:Breadcrumb">
    <a title="Go to Innomations." href="" class="home">Home</a></span>
  >>
  <span typeof="v:Breadcrumb" class="turnoffmain">
    <a rel="v:url" property="v:title" title="Go to Products." href="">Products</a></span> 
</div>

关于javascript - 使用 jquery 删除两个跨度之间的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32709728/

相关文章:

javascript - 为什么属性名称中的引号会引发错误?

html - CSS 颜色不加载按钮

javascript - 平滑滚动不适用于哈希 URL

javascript - 将更多内容加载到页面后,Bootstrap Affix 不起作用

javascript - 查找嵌套对象

javascript - 如何改变相反方向的导航栏动画?

Javascript:文本替换数组中的多个字符串?

javascript - 图像上的可缩放拼图的 CSS

javascript - Google Apps编写自定义每小时触发器以在给定时间启动

Jquery:查找子div的高度并更改父div的高度