![](/img/trans.png)
[英]Remove everything inside div but keep children with specific class name
[英]Remove div with specific children dynamically
我的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>
我想獲取divs中最里面的span的文本,它有兩個嵌套的span,最里面的span應該有一個標題,例如
<div>
<span>
<span title="title 2">
Some other text written here
</span>
</span>
</div>
並且也有可能刪除這種股利? jquery中有任何函數可以做到嗎? 提前致謝
由於里面沒有其他文本,因此您可以在外部div上簡單地使用.textContent
並trim
結果:
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);
<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>
您可以使用$('div > span > span')
定位這些元素,並使用.each()
遍歷它們。
您可以使用.text()
方法獲取文本內容,並使用.remove()
刪除元素。
可以在以下內容中看到:
$('div > span > span').each(function() { console.log($(this).text()); $(this).remove(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <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>
不需要jQuery,選擇的答案不會檢查title屬性,也不會刪除div(它會刪除跨度):
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.