简体   繁体   中英

Converting HTML Element into 'Node' type

I'm working on a HTML project. Basically saving HTML nodes to a JavaScript's Object to append them inside a element. Here's my HTML, JavaScript and the error.

HTML

...
    <div id="holder"></div>
...

JavaScript

var _handler = {};
var _holder = document.getElementById('holder');
var some_example = [{"id":"item_1"}, {"id":"item_2"}]

function create(tag, id) { /*Created a DOMObject */
    var elem = document.createElement(tag);
    _handler[id] = elem;
}
function spawn() {
   for (var k in _handler) {
       _holder.appendChild(_handler[k]); //<----- Here's the error occurring, given at very last.
   }
}
function main() { /* Main function */
    for (var x=0;x < some_example.length;x++) {
         create('div', some_example.id);
    }
    spawn();
}

Sorry for that little complicated script. Anyways, all the work going great but, appendChild does the bobo given below:

Error

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

Hope, you guys have any idea. Thank You.

Make sure you use hasOwnProperty in your for loop.

for (var k in _handler) {
   if (_handler.hasOwnProperty(k)) {
       _holder.appendChild(_handler[k]); 
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM