Broshi
Broshi

Reputation: 3592

Extract text outside HTML tag with jQuery

Lets say I have the following markup: <a href="#">My Link <span>And More</span></a> How can I extract only My Link with jQuery without the content of the <span>?

Upvotes: 1

Views: 972

Answers (4)

M. Salah
M. Salah

Reputation: 681

var htmlTags = '<span class="prinse-txt">This is my test text</span>';
var textFromHtmlTags = $(htmlTags).text()

Upvotes: 0

Subhasis Maity
Subhasis Maity

Reputation: 11

var txt1 = $('a').text();
var txt2 = $('a').children().text();
var ret = txt1.slice(0, txt1.indexOf(txt2));
console.log(ret);

Upvotes: 0

Inanda Menezes
Inanda Menezes

Reputation: 1804

From: 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

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

Filter it out using the nodeType:

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

-DEMO-

Upvotes: 7

Related Questions