假设我有以下标记:
<a href="#">My Link <span>And More</span></a>
如何在没有My Link
的内容的情况下仅使用jQuery提取<span>
?
答案 0 :(得分:7)
使用nodeType:
过滤掉它var txt = $('a').contents().filter(function(){
return this.nodeType === 3;
}).text();
答案 1 :(得分:0)
来自:https://javahelpworld.wordpress.com/2014/04/14/jquery-get-the-text-of-element-without-child-element/
jQuery.fn.justtext = function() {
return $(this) .clone()
.children()
.remove()
.end()
.text();
};
$('a').justtext(); //call like this for any element
答案 2 :(得分:0)
var txt1 = $('a').text();
var txt2 = $('a').children().text();
var ret = txt1.slice(0, txt1.indexOf(txt2));
console.log(ret);
答案 3 :(得分:0)
var htmlTags = '<span class="prinse-txt">This is my test text</span>';
var textFromHtmlTags = $(htmlTags).text()