Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get content between <div> tags

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.

like image 986
user460114 Avatar asked Jul 28 '11 04:07

user460114


People also ask

How to get contents of div in jQuery?

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.

How to get the text of div?

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.

How to get the text of an element in jQuery?

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.

Which method in jQuery removes the selected elements from HTML?

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.


2 Answers

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 divs 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

  1. get the length of the string.
  2. find out where the first div occurs
  3. slice the content there.
like image 152
Jason Gennaro Avatar answered Sep 22 '22 10:09

Jason Gennaro


jQuery has two methods

// First. Get content as HTML $("#my_div_id").html();  // Second. Get content as text $("#my_div_id").text(); 
like image 27
oknoorap Avatar answered Sep 23 '22 10:09

oknoorap