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

时间:2016-09-28 09:59:21

标签: javascript jquery html nextsibling

链接在这里; http://heart.bmj.com/content/early/2016/08/10/heartjnl-2016-310003.long

我有;

<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的范围并获取原始文本?

6 个答案:

答案 0 :(得分:0)

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

&#13;
&#13;
var text = $(".cit-title > .cit-series-title")[0].nextSibling.textContent;
console.log(text);
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以先获取整个cit-title元素的内容......

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

...然后只获得标题文字......

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

... 然后titleText

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

答案 2 :(得分:0)

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

然后像A.replace(B, '');那样工作

答案 3 :(得分:0)

&#13;
&#13;
alert($(".cit-title").clone()    
           .children() 
           .remove()   
           .end()      
          .text());
&#13;
<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>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

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

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

答案 5 :(得分:-1)

我认为更好的解决方案是将其他文本包装在另一个范围内,如下所示:

<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获取内部文本,而不是形成容器。

干杯