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.
You could use $('. gettext'). text(); 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With