![](/img/trans.png)
[英]How to Get A Element First Child Text Using Jquery And Class Selector?
[英]Get text of div with child element using jQuery
在以下示例中:
<div id="mainDiv">
<h1>The <span class="bold">title</span></h1>
some text
<p>and again</p>
<p>another text.</p>
</div>
我正在嘗試將所有文本放在一個字符串中。 當我只執行$('#mainDiv').text()
它將文本返回為The titlesome textand againanother text
返回為The titlesome textand againanother text
。
在這種情況下,我希望子元素中的單詞之間有空格。 所以我非常接近地做:
if ($('#mainDiv').find("*").length >= 1) {
$('#mainDiv').find("*").each(function () {
sFullText = sFullText + $(this).text().trim().replace(/\s\s+/g, ' ') + ' ';
});
}
現在的結果是: The titlesome textand again another text
。
因此,當所有文本都在子元素中時有效,但是如果某些文本在mainDiv
中則mainDiv
。 (頁面及其內容是動態的,所以我不知道mainDiv
有哪些特定元素)
從此處使用jQuery插件: http : //viralpatel.net/blogs/jquery-get-text-element-without-child-element/
jQuery.fn.justtext = function() {
return $(this) .clone()
.children()
.remove()
.end()
.text();
};
// ...
var sFullText = $('#mainDiv').justtext();
if ($('#mainDiv').find("*").length >= 1) {
$('#mainDiv').find("*").each(function () {
sFullText = sFullText + ' ' + $(this).text().trim().replace(/\s\s+/g, ' ');
});
}
我相信當您放平html時,您的問題就存在了:
<div id="mainDiv" style="display:none;"><h1>The <span class="bold">title</span></h1>some text<p>and again</p><p>another text.</p></div>
<div id="result"></div>
$("#result").html($("#mainDiv").text());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.