Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get content of div which contains JavaScript script blocks?

I have the following HTML

<div id="example">
  ...some text...
  <script type="text/javascript">
    ... some javascript...
  </script>
</div>

How to get content of #example but also with the JavaScript?

$("#example").html(),
$("#example").text(),     
$("#example").val()     

all don't work.

like image 226
mm. Avatar asked Sep 16 '09 09:09

mm.


People also ask

How do I get the content of a 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.

Can we use script tag inside div?

You can add <script></script> inside a DIV tag. Just check on w3c, it is valid HTML. Save this answer.

How do I get text inside a div using 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.


2 Answers

The html() method should work for you. Are you sure you are running the code after the DOM is completed?

$(document).ready(function(){
   alert($("#example").html());
});
like image 139
aolde Avatar answered Oct 20 '22 05:10

aolde


Working Demo

You can use

html(): Get the html contents (innerHTML) of the first matched element.

var contents = $("#example").html();
like image 21
rahul Avatar answered Oct 20 '22 04:10

rahul