Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Get tag content excluding nested tags

I've got some HTML like the following:

<span id="A">Text I'm interested in
  <span id="B">Other crap I don't care about</span>
</span>

I'm looking to get the text content of span "A" excluding any nested tags (i.e. the content of span "B" in the above example). I'm trying to get the text content, not the HTML content. Also, in my particular case, I know there will always be some text inside of span A prior to any other tags, but I'm interested in the less-constrained solution as well.

The simple-but-clunky approach I've considered going with is just doing $("#A").html() and then parsing through until I hit an unescaped "<" but it feels like there should be a cleaner solution.

like image 668
Dane B Avatar asked Jan 05 '10 15:01

Dane B


People also ask

How do I get just the text from HTML in jQuery?

You could use $('. gettext'). text(); in jQuery.

How to remove content from div in jQuery?

To remove elements and content, there are mainly two jQuery methods: remove() - Removes the selected element (and its child elements) empty() - Removes the child elements from the selected element.

How to remove DOM element in jQuery?

remove() method takes elements out of the DOM. Use . remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

How to prepend element in jQuery?

The prepend() method inserts specified content at the beginning of the selected elements. Tip: To insert content at the end of the selected elements, use the append() method.


1 Answers

I'm fairly sure there's no built in way to do it - although you could look for a plugin, it may exist. Someone else posted the .text() method (but deleted the post) which will get you ALL the text, minus the tags, which means you'll get "Text I'm interested in Other crap I don't care about" -- not what you want.

EDIT

Okay, I decided I was interested in this so I spent some time. Here's the solution :)

    copyOf = $('#A').clone();
    copysKids = copyOf.children();
    copysKids.remove();

    alert(copyOf.text());

What we're doing is making a clone of the node you're trying to get text out of - we don't want to operate on the original because this would change the page. Then we're grabbing a collection of all the child nodes, and nuking them. The remaining text is the text you were looking for.

like image 87
Erik Avatar answered Oct 16 '22 12:10

Erik