Get content of a DIV using JavaScript

前端 未结 5 1890
自闭症患者
自闭症患者 2020-11-27 03:08

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 cod

5条回答
  •  猫巷女王i
    2020-11-27 03:47

    Right now you're setting the innerHTML to an entire div element; you want to set it to just the innerHTML. Also, I think you want MyDiv2.innerHTML = MyDiv 1 .innerHTML. Also, I think the argument to document.getElementById is case sensitive. You were passing Div2 when you wanted DIV2

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

    Also, this code will run before your DOM is ready. You can either put this script at the bottom of your body like paislee said, or put it in your body's onload function

    
    

    and then

    function loadFunction(){
        var MyDiv1 = Document.getElementById('DIV1');
        var MyDiv2 = Document.getElementById('DIV2');
        MyDiv2.innerHTML = MyDiv1.innerHTML; 
    }
    

提交回复
热议问题