[英]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.