如何使用javascript获取span内部的文本内容?

问题描述:

链接在这里; http://heart.bmj.com/content/early/2016/08/10/heartjnl-2016-310003.long如何使用javascript获取span内部的文本内容?

我有;

<span class="cit-title"> 
    <span class="cit-series-title">Original article 
     <span class="cit-sep cit-sep-after-article-series-title">:</span> 
    </span>Pregnancy outcomes in patients with pulmonary arterial hypertension associated with congenital heart disease 
</span> 

到目前为止我做了什么?

我选择span.cit-title但它innerText

给我;

"Original article: Pregnancy outcomes in patients with pulmonary arterial hypertension associated with congenital heart disease" 

我想只有

"Pregnancy outcomes in patients with pulmonary arterial hypertension associated with congenital heart disease"` 

一部分。

如何排除类别为cit-series-title的跨度并获取原始文本?

+3

这是http://*.com/questions/6520192/get-text-node-of-an-element的副本。你会在那里找到你的答案。 – Max

+0

是否真的需要很多跨度? – vamsi

+0

我尝试解析html。所以我不是跨度的作者。 :) – user6468132

我认为更好的解决办法是包装在另一个这样跨度的其他文字:

<span class="cit-title"> 
 
    <span class="cit-series-title">Original article<span class="cit-sep cit-sep-after-article-series-title">:</span> </span><span class="cit-series-description">Pregnancy outcomes in patients with pulmonary arterial hypertension associated with congenital heart disease</span> </span>

然后你从.cit-series-description内部文本,而不是形成容器。

干杯

你想要的文字是.cit-series-title下一个兄弟。您可以选择该元素并使用javascript Node.nextSibling获取它的下一个兄弟文本。

var text = $(".cit-title > .cit-series-title")[0].nextSibling.textContent; 
 
console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="cit-title"> 
 
    <span class="cit-series-title">Original article 
 
     <span class="cit-sep cit-sep-after-article-series-title">:</span> 
 
    </span>Pregnancy outcomes in patients with pulmonary arterial hypertension associated with congenital heart disease 
 
</span>

你可以先把整个cit-title元素的内容...

var wholeElementText = $('.cit-title').text(); 

...那么得到的只是标题文字...

var titleText = $('.cit-title .cit-series-title').text(); 

...和然后wholeElementText

var justThePartYouWant = wholeElementText.replace(titleText, ''); 

选择数据从span.cit-title删除titleText并将其存储到变量A,然后从span.cit-series-title选择数据并将其存储到变量B

那么不喜欢A.replace(B, '');它会工作

alert($(".cit-title").clone()  
 
      .children() 
 
      .remove() 
 
      .end()  
 
      .text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="cit-title"> 
 
    <span class="cit-series-title">Original article 
 
     <span class="cit-sep cit-sep-after-article-series-title">:</span> 
 
    </span>Pregnancy outcomes in patients with pulmonary arterial hypertension associated with congenital heart disease 
 
</span>

我会将div存储在临时变量中以删除不需要的元素并获取文本。

var div = $(".cit-title").clone(); 
div.find("span").first().remove(); 
div.text();