This'll probably be easy for someone:
var x = '<p>blah</p><div><a href="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=brd&FlightID=2997227&Page=&PluID=0&Pos=9088" target="_blank"><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></a></div>';
How do I extract only the portion between the div tags <div>I want this</div>
Don't focus on the <a>
tag as the content could be different inside the div.
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 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.
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.
This is probably what you need:
$('div').html();
demo
This says get the div
and return all the contents inside it. See more here: http://api.jquery.com/html/
If you had many div
s on the page and needed to target just one, you could set an id
on the div
and call it like so
$('#whatever').html();
where whatever is the id
EDIT
Now that you have clarified your question re this being a string, here is a way to do it with vanilla js:
var l = x.length; var y = x.indexOf('<div>'); var s = x.slice(y,l); alert(s);
Demo Here
div
occursjQuery has two methods
// First. Get content as HTML $("#my_div_id").html(); // Second. Get content as text $("#my_div_id").text();
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