Scott Simpson
Scott Simpson

Reputation: 3850

Getting text from inside P element, not including span tag in selection

How do I remove the span element from the selection in order to get just the text in the P tag, and not include the span tag or its contents?

<p><span class="title visible-xs-inline">Description: </span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

I have tried using .not(), but that doesn't work in this case.

var theValue = $(this).parents().find('p').not('.title').text();

Upvotes: 1

Views: 1000

Answers (2)

Brino
Brino

Reputation: 2502

This answer provides an excellent example. Just clone the element in memory and remove its children, then call .text().

$('button').click(function() {
  var text = $("p")
    .clone() //clone the element
    .children() //select all the children
    .remove() //remove all the children
    .end() //again go back to selected element
    .text();
  alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><span class="title visible-xs-inline">Description: </span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

<button>Get P Text Not Including Span</button>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337713

Due to the HTML structure you would need to retrieve the textNode itself. Try this:

var text = $('p').contents().last()[0].nodeValue;

Example fiddle

Upvotes: 1

Related Questions