Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get content of a DIV using JavaScript

Tags:

javascript

I have two DIV's called DIV1 and DIV2 and DIV1 consists of dynamic content and DIV2 is empty. I need content of DIV1 to be displayed in DIV2. How can I do it.

I coded in below manner which is not working. Anybody please correct it.

<script type="text/javascript">     var MyDiv1 = Document.getElementById('DIV1');    var MyDiv2 = Document.getElementById('Div2');    MyDiv2.innerHTML = MyDiv2;   </script> <body> <div id="DIV1">  // Some content goes here. </div>  <div id="DIV2"> </div> </body> 
like image 687
Karthik Malla Avatar asked Dec 27 '11 17:12

Karthik Malla


People also ask

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.

Can a div have a value attribute?

An <div> element can have any number of data-* attributes, each with their own name. Using data-* attributes reduces the need for requests to the server. Note: The data-* attribute is not visible and does not change the appearance of the div element.


2 Answers

(1) Your <script> tag should be placed before the closing </body> tag. Your JavaScript is trying to manipulate HTML elements that haven't been loaded into the DOM yet.
(2) Your assignment of HTML content looks jumbled.
(3) Be consistent with the case in your element ID, i.e. 'DIV2' vs 'Div2'
(4) User lower case for 'document' object (credit: ThatOtherPerson)

<body> <div id="DIV1">  // Some content goes here. </div>  <div id="DIV2"> </div> <script type="text/javascript">     var MyDiv1 = document.getElementById('DIV1');    var MyDiv2 = document.getElementById('DIV2');    MyDiv2.innerHTML = MyDiv1.innerHTML;  </script> </body> 
like image 112
calebds Avatar answered Oct 11 '22 10:10

calebds


You need to set Div2 to Div1's innerHTML. Also, JavaScript is case sensitive - in your HTML, the id Div2 is DIV2. Also, you should use document, not Document:

var MyDiv1 = document.getElementById('DIV1'); var MyDiv2 = document.getElementById('DIV2'); MyDiv2.innerHTML = MyDiv1.innerHTML;  

Here is a JSFiddle: http://jsfiddle.net/gFN6r/.

like image 38
ThatOtherPerson Avatar answered Oct 11 '22 08:10

ThatOtherPerson