Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add HTML elements dynamically with JavaScript inside DIV with specific ID

Tags:

javascript

Ok, people, I need your help. I've found some code here on Stackoverflow (can't find that link) which generate HTML code dynamically via JS. Here is code:

function create(htmlStr) {
    var frag = document.createDocumentFragment(),
        temp = document.createElement('div');
    temp.innerHTML = htmlStr;
    while (temp.firstChild) {
        frag.appendChild(temp.firstChild);
      }
        return frag;
    }

    var fragment = create('<div class="someclass"><a href="www.example.com"><p>some text</p></a></div>'); 

    document.body.insertBefore(fragment, document.body.childNodes[0]);

This code works just fine! But the generated code appears on top of page, right below body tag. I would like to generate that code inside empty div with specific id="generate-here".

So output will be:

<div id="generate-here">
    <!-- Here is generated content -->
</div>

I know that I can't see generated content with "view source". I only need to generate that content just in this particular place with #generate-here. I'm Javascript noob, so if anyone can just rearrange this code that will be perfect. Thanks a lot!

P.S. I know how to do this with Jquery, but I need native and pure JavaScript in this case.

like image 448
Miljan Puzović Avatar asked Aug 04 '12 01:08

Miljan Puzović


People also ask

Can HTML elements be create dynamically using JavaScript?

New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method.

How dynamically add HTML element using jQuery?

$(document). ready(function() { $('body'). on('click', '. AddEl', function() { var $elems = $('.


1 Answers

All you need to do is change the last line. This will add the created element as the last child of the div:

document.getElementById("generate-here").appendChild(fragment);      

This will add the created element as the first child of the div:

var generateHere = document.getElementById("generate-here"); generateHere.insertBefore(fragment, generateHere.firstChild); 

You can also use innerHTML to just replace everything with new text (as you do in your create function). Obviously this one doesn't require you to keep the create function because you need an html string instead of a DOM object.

var generateHere = document.getElementById("generate-here"); generateHere.innerHTML = '<div class="someclass"><a href="www.example.com"><p>some text</p></a></div>'; 
like image 120
Gordon Gustafson Avatar answered Sep 25 '22 00:09

Gordon Gustafson