如何使用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
的跨度并获取原始文本?
答
我认为更好的解决办法是包装在另一个这样跨度的其他文字:
<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();
这是http://*.com/questions/6520192/get-text-node-of-an-element的副本。你会在那里找到你的答案。 – Max
是否真的需要很多跨度? – vamsi
我尝试解析html。所以我不是跨度的作者。 :) – user6468132