tags:

views:

50

answers:

2

I have a list and each item has a button. When I click the button I want a div to appear within the list item. The contents of this appearing div will be the same for each list item. How do I dynamically generate these divs using Javascript?

I've investigated the createElement() function but have yet to grasp its use or find a good example.

+1  A: 

Hi Charlie,

You can use document.createElement(), but it's not really way you want to do it (mostly because of performance).

What you really need to do is to have your DIV as part of your markup, but make it invisible with CSS. And then just copy it to LI innerHTML.

Something like this:

CSS:
.hidden-element
{
   display:none;
}

HTML:
<ul>
  <li id="firstListItem"></li>
</ul>

<div  id="myDiv" class="hidden-element">
     <div>My Div Content</div>
</div>

JavaScript:

function showDivContent()
{
 var listItem = document.getElementById('firstListItem');
 var myContent = document.getElementById('myDiv').innerHTML;
 listItem.innerHTML = myContent;
}
dimarzionist
I like this solution. Couple questions though. Can I do something like:`listItem.innerHTML += myContent;//Append`Or is there an append comand I should use?Secondly, what if that nested div within the hidden-element has an onclick() handler. Can I programtically change the function parameters of that onclick() handler.?
Charlie
Yes, you can append the content, innerHTML is the simple string for JS. If your parameters for onclick event are dependent on DIV itself, then it's better to pass this as parameter:onclick="myFunction(this);"Alternatively you can assign onclick handler dynamically when you adding DIV element itself:firstListItem.innerHTML = myContent;for(var j=0; j<firstListItem.childNodes.length; j++){ if(firstListItem.childNodes[j].tagName == 'DIV') //ideally check for id firstListItem.childNodes[j].onclick = function () {alert('Test me!');};}Or even better use jQuery.bind() :)Good luck!
dimarzionist
The supposed performance issue with `document.createElement()` is only a concern if you're using it to create loads of elements. For a few elements, it's never going to be an issue, and has significant advantages over `innerHTML`.
Tim Down
It's true. However when I don't know how complex is the inner content of the div is going to be I'd go with innerHTML and let browser rendering engine do it work :) I'm using here the same approach as for StringBuilder usage - if it's big number of strings or idk exact number I'll use it. Cheers
dimarzionist
A: 
var newDiv = document.createElement("div") // You now have an HTMLFragment
    newDiv.id = "Something"
document.body.appendChild(newDiv) // The body now has a new div appended to it. 
John
`HTMLFragment`? Perhaps you're confusing `document.createElement()` with `document.createDocumentFragment()`. `document.createElement()` creates an element.
Tim Down
I thought anything that was not yet tied down to the dom was considered a "fragment", my bad.
John