0

The following is a simplified excerpt from my code:

$('a').on('click', function()
{
    // Get the text from the link
    var textIwantToUse = $(this).text();

    // Set the elements text to that of the link
    $('elementIwantToPassTheTextTo').text(textIwantToUse);
}

The problem I have is the link contains a span with some text I don't want:

<a href="#">I want this text <span>but not this</span></a>

How can I remove the text in the span tag before I pass it to the target element?

Many thanks in advance.

mtwallet
  • 5,040
  • 14
  • 50
  • 74

5 Answers5

2

use .contents() and .filter to select only text nodes, then grab the text of those:

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

$('elementIwantToPassTheTextTo').text(txt);

Example: http://jsfiddle.net/S95Ls/

Community
  • 1
  • 1
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
1

If you get the html so that it includes the <span> tags you can then split on the and use everything before it.

var textIwantToUse = $(this).html().split('<span>')[0];
Jonathan
  • 1,833
  • 13
  • 15
1

By cleaning up html tag :

var textIwantToUse = $(this).html().replace(/<span>.*<\/span>/ig, '');
user3041160
  • 684
  • 3
  • 5
0

You can do it like this to remove only inner text from span:

$(this).find('spam').html('');

This will remove text in the span element, or you can also remove entire span element if you would like it like this:

$(this).remove('span')

then do else what you like...

var textIwantToUse = $(this).text();
var textIwantToUse = $(this).html();
// or whatever you want to do with it
Hrvoje Golcic
  • 3,446
  • 1
  • 29
  • 33
0

Try:

$('a').on('click', function () {
    var textIwantToUse = $(this).html();
    $('.elementIwantToPassTheTextTo').html(textIwantToUse);
    $('.elementIwantToPassTheTextTo').find("span").remove();
});

DEMO here.

codingrose
  • 15,563
  • 11
  • 39
  • 58