Why this design does not work?

If you pull out from div user div data - it will work.

But, alas, I can not understand.

And the task in front of me is this - I have an array like this, there are several id in it, I want to put its lastname into the first div, and below in another div, for example, I don’t quite understand how to do this:

John Lastname //div user Skype : 123 //div userExt Dan Qwert //div user? Skype : 456 // div userExt? 

Provided that all this will be in the array (I mean several skype and correspondingly, several full names)

 window.onload = function() { var person = { id: 1, firstName: "John", lastName: "Doe", age: 46, instagram: 123, skype: "Lamp" }; var user = person['firstName'] + ' ' + person['lastName']; var userExt = person['id'] + ' ' + person['age']; document.getElementById("user").innerHTML = user; document.getElementById("data").innerHTML = userExt; //console.log (data); }; 
 <div id="user"> <div id="data"> </div> </div> 

  • Let me clarify why I want to display about a single user in different divas - logically sometime later, I will need to hide, by the conditions, these same divas of the lower level. - Super
  • You have one div overwrites another, you need to "untie" them like so <div><span id=user /><div id=data /></div> and then by writing down the user you delete the data. - nick_n_a

2 answers 2

 window.onload = function() { var person = { id: 1, firstName: "John", lastName: "Doe", age: 46, instagram: 123, skype: "Lamp" }; var user = person['firstName'] + ' ' + person['lastName']; var userExt = person['id'] + ' ' + person['age']; var data = document.getElementById("data").innerHTML = userExt; document.getElementById("user").innerHTML = user + data; //console.log (data); }; 
 <div id="user"> <div id="data"> </div> </div> 
When you change the value via document.getElementById ("user"). InnerHTML, all the contents of the diva are overwritten (including all embedded divs and text), you can copy the entire contents of the diva in advance and then add it, or untie the divs

 <div> <div id="user"> </div> <div id="data"> </div> </div> 

  • do not call document.getElementById ("user"). innerHTML , but change the value of document.getElementById ("user"). innerHTML - Grundy

You have two user and userExt string variables.

  1. When you write document.getElementById ("user"). InnerHTML = user; then your code

 <div id="user"> <div id="data"> </div> </div> Становится таким: <div id="user">"тут написано значение переменной user"</div> 

  1. When you write document.getElementById ("data"). InnerHTML = userExt; , the interpreter cannot find the div # data object, since it DOES NOT EXIST in memory. That gives an error.