Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

innerHTML inserts only [object HTMLDivElement]

i want to insert a htmlsnippet into another html-element

i tried it this way

the html

<div class="box1">
    insert this html element
</div>
<div class="box2">
  into this
</div>

the js

var box1 = document.querySelectorAll(".box1")[0]; 
var box2 = document.querySelectorAll(".box2")[0];
console.log(box1);
box2.innerHTML = box1;

but it doesnt work it only insert [object HTMLDivElement], if i look at the console it puts out the correct html, what im doing it wrong?

and yeah i dont want to use the $ libary ;)

http://codepen.io/destroy90210/pen/MKQOwy

thanks ;)

like image 776
Gregor Voinov Avatar asked Jan 23 '16 16:01

Gregor Voinov


People also ask

How do you parse an object in HTMLDivElement?

Just clone the container whose nodes you want to copy and get the nodes from the copied one, if you want to make the original container intact. And you are putting them into the array and then running a loop multiple times instead you can run a loop once and simultaneously put them in your .

How use innerHTML with div tag?

Using the innerHTML attribute: To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.

How do I change innerHTML content?

To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.

Is innerHTML an object?

The innerHTML property is a part of the Document Object Model (DOM) that is used to set or return the HTML content of an element.


2 Answers

innerHTML doesn't insert DOM nodes, just strings.
Use appendChild instead

var box1 = document.querySelector(".box1"); 
var box2 = document.querySelector(".box2");

box2.appendChild( box1 );
like image 104
adeneo Avatar answered Nov 08 '22 12:11

adeneo


You should use the appendChild method.

box2.appendChild(box1);
like image 32
Bojan Rosko Avatar answered Nov 08 '22 11:11

Bojan Rosko