2017-10-17 50 views
1

我正在重新列表li中的相關文章的列表,並且我希望刪除標籤和span之間的」 - 「而不會混淆原始內容。頁面(鏈接)上,我必須使用jQuery,我不知道是否有這樣做的一個簡單的方法jQuery if list item contains'' - 「.remove()?

<div class="related-articles card"> 
<h3 class="h2"> 
    <i class="fa fa-book text-brand-primary-dark"></i> Related Articles 
</h3> 

<ul> 

<li> 
    <a href="http://example.com/article-1">Title One</a> 
      - 
    <span> Some Related Preview Text... </span> 
</li> 
    <li> 
    <a href="http://example.com/article-2">Title Two</a> 
      - 
    <span> Some Related Preview Text... </span> 
</li> 
    <li> 
    <a href="http://example.com/article-3">Title Three</a> 
      - 
    <span> Some RelatedPreview Text... </span> 
</li> 
</ul> 

回答

0

一種選擇是:

$('.related-articles li a').map(function() { 
    return this.nextSibling; 
}).remove(); 
1

這裏是我的解決方案,獲取子元素並將其分配,所以純文本(-)將被刪除!

$('.related-articles li').each(function() { 
 
    $(this).html($(this).children()); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="related-articles card"> 
 
    <h3 class="h2"> 
 
    <i class="fa fa-book text-brand-primary-dark"></i> Related Articles 
 
    </h3> 
 

 
    <ul> 
 

 
    <li> 
 
     <a href="http://example.com/article-1">Title One</a> - 
 
     <span> Some Related Preview Text... </span> 
 
    </li> 
 
    <li> 
 
     <a href="http://example.com/article-2">Title Two</a> - 
 
     <span> Some Related Preview Text... </span> 
 
    </li> 
 
    <li> 
 
     <a href="http://example.com/article-3">Title Three</a> - 
 
     <span> Some RelatedPreview Text... </span> 
 
    </li> 
 
    </ul>

1

一種方式將是對循環通過每個<li>,提取<a><span>元件和手動縫合在一起它們,這樣的:

$("ul > li").each((i, li) => { 
 
    const $li = $(li); 
 
    const $a = $li.find("a"); 
 
    const $span = $li.find("span"); 
 
    
 
    //create a temp element with just the <a> and <span> 
 
    const $tempItem = $("<li></li>");  
 
    $tempItem.append($a).append($span); 
 
    //copy new HTML into old element 
 
    $li.html($tempItem.html()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<ul> 
 

 
<li> 
 
    <a href="http://example.com/article-1">Title One</a> 
 
      - 
 
    <span> Some Related Preview Text... </span> 
 
</li> 
 
    <li> 
 
    <a href="http://example.com/article-2">Title Two</a> 
 
      - 
 
    <span> Some Related Preview Text... </span> 
 
</li> 
 
    <li> 
 
    <a href="http://example.com/article-3">Title Three</a> 
 
      - 
 
    <span> Some RelatedPreview Text... </span> 
 
</li> 
 
</ul>

+0

納倫的回答是bette雖然! –