动态删除特定子项的div

时间:2018-03-23 01:56:17

标签: javascript jquery html

我的HTML代码中有很多分歧。任何div都没有id或类。这是我的代码

<div>
<span>
<a href="#">
  link</a>
</span>
</div>

<div>
<span>
<span title=" title 1">
Some text written here
</span>
</span>
</div>

<div>
<span>
<span title="title 2">
Some other text written here
</span>
</span>
</div>

<div>
<span>
<a href="#">
some link
</a>
</span>
</div>

我想得到div内部跨度的文本,它有两个嵌套的跨度,最里面的跨度应该有一个标题,如

<div>
<span>
<span title="title 2">
Some other text written here
</span>
</span>
</div>

也可以删除这些div吗?在jquery中有任何函数可以做到吗?提前谢谢

3 个答案:

答案 0 :(得分:1)

由于里面没有其他文字,您只需在外部div上使用.textContent,然后在trim使用结果:

&#13;
&#13;
const texts = [];
document.querySelectorAll('div').forEach(div => {
  if (
    div.children[0].tagName !== 'SPAN' ||
    div.children[0].children[0].tagName !== 'SPAN' ||
    !div.children[0].children[0].hasAttribute('title')
  ){
    return;
  }
  texts.push(div.textContent.trim());
  // if you want to remove the divs afterwards:
  div.remove();
});
console.log(texts);
&#13;
<div>
<span>
<a href="#">
  link</a>
</span>
</div>

<div>
<span>
<span title=" title 1">
Some text written here
</span>
</span>
</div>

<div>
<span>
<span title="title 2">
Some other text written here
</span>
</span>
</div>

<div>
<span>
<span>
some span without a title
</span>
</span>
</div>

<div>
<span>
<a href="#">
some link
</a>
</span>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用kmodes定位这些元素,并使用 .each() 循环播放这些元素。

您可以使用 .text() 方法获取文字内容,并使用 .remove() 删除元素。

这可以在以下内容中看到:

$('div > span > span')
$('div > span > span').each(function() {
  console.log($(this).text());
  $(this).remove();
});

答案 2 :(得分:0)

不需要这个jQuery,选择的答案不检查title属性,也不删除div(它删除了span):

const data = Array.from(
  document.querySelectorAll("#content>div>span>span[title]")
).map(
  span=>[span.parentElement.parentElement,span.textContent.trim()]
);

console.log(
  "text content of element(s):",
  JSON.stringify(
    data.map(([x,text])=>text)
  )
);
setTimeout(
  ()=>{
    alert("before removing divs (check html)");
    data.forEach(([div])=>div.remove());
  },2000
)
    <div id="content">

      <div>
        <span>
        <a href="#">
          link</a>
        </span>
        </div>
        
        <div>
        <span>
        <span title=" title 1">
        Some text written here
        </span>
        </span>
        </div>
        
        <div>
        <span>
        <span title="title 2">
        Some other text written here
        </span>
        </span>
        </div>
        
        <div>
        <span>
        <a href="#">
        some link
        </a>
        </span>
        </div>

    </div>