使用 jQuery 提取 HTML 标记之外的文本

Extract text outside HTML tag with jQuery

本文关键字:文本 jQuery 提取 HTML 使用      更新时间:2023-09-26

假设我有以下标记: <a href="#">My Link <span>And More</span></a>如何仅使用 jQuery 提取My Link而没有<span>的内容?

使用 nodeType 过滤掉它:

var txt = $('a').contents().filter(function(){
    return this.nodeType === 3;
}).text();

-演示-

发件人: 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
var txt1 = $('a').text();
var txt2 = $('a').children().text();
var ret = txt1.slice(0, txt1.indexOf(txt2));
console.log(ret);
var htmlTags = '<span class="prinse-txt">This is my test text</span>';
var textFromHtmlTags = $(htmlTags).text()