Let's consider following html code:
<p>
Some text followed by <span>a span element</span>
and another text followed by <b>a bold text</b>.
</p>
How can I get the text before the span
and b
elements using jQuery?
I tried $("span").prev()
and $("b").prev()
but it did work because the text is not an element. I also tried $("span").parent()
but it matched whole paragraph, while I want only a part of it.
Could you advise any solution? Thank you in advance :-)
To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.
Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.
before( function ) A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument.
Use the textContent property to get the text of a div element, e.g. const result = element. textContent . The textContent property will return the text content of the div and its descendants. If the element is empty, an empty string is returned.
Answer: Use the jQuery text () method You can simply use the jQuery text () method to get all the text content inside an element. The text () method also return the text content of child elements. Let's take a look at an example to understand how this method basically works:
jQuery text() Method jQuery HTML/CSS Methods. Example. ... Definition and Usage. The text() method sets or returns the text content of the selected elements. When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed).
.before( content content ] )Returns: jQuery. Description: Insert content, specified by the parameter, before each element in the set of matched elements. HTML string, DOM element, text node, array of elements and text nodes, or jQuery object to insert before each element in the set of matched elements.
Jquery get content methods like text(), html(), val() and attr() can be used to get the content of the HTML element. These methods when calls for getter method
How about collecting them into an array instead of two calls to $
:
var texts = $('span, b').map(function(){
return this.previousSibling.nodeValue
});
texts[0]; // "Some text followed by "
texts[1]; // " and another text followed by "
References:
previousSibling
property 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