2

I have a dynamically added div which I want to append in response to a click event. The initial div is created and rendered when added however trying to add children divs to the first dynamic div does not render - yet in console log the dynamic div shows the new div has been added.

var newDiv = $('<div id="#newDiv'+pID+'" />').css({
    display:"inline-block",
    width:"90%",
    height:"100px",
    position:"relative"
})

var newHTML = "<div>some content</div>"

$(newDiv).html(newHTML)
$('#dynDiv'+ID).append($(newDiv))

console.log($('#dynDiv'+pID))  // displays code created successfully

So newDiv is not rendered nor present when "inspecting" the DOM using debugger.

Why is the second attempt to add dynamic content failing ??

1
  • Do not add hash mark in id property: '<div id="newDiv'+pID+'"' Commented Jul 4, 2014 at 15:37

3 Answers 3

1

Have you remembered to append it to something? Remember, jQuery can have DOM elements present in memory which are not part of the page:

newDiv.appendTo($(parentElement));

eg. http://jsfiddle.net/dTe73/

A couple of other possible errors:

  • # is not a valid character to put in an id in $('<div id="#newDiv'+pID+'" />')
  • $('#dynDiv'+ID) looks like a typo for $('#dynDiv'+pID) (or the other way around)
  • Not an actual error, but redundant use of $: $(newDiv) is absolutely equivalent to newDiv
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks - made the suggested changes with no change in the results - still not in the DOM...
@BenMarchbanks Well as you can see in the attached fiddle, the code you posted works perfectly fine. I'd look for the problem elsewhere. Do you have an error log? Have you tried debugging?
The fiddle example does not add an element to the DOM - it only dumps the contents to console.log - this I can do in my original code - even though the console.log shows the results the element is not added to the DOM - I must add a important detail - the target dynDiv was originally added dynamically - in my sample code I am trying to add another dynamic div which is failing to render
@BenMarchbanks The fiddle is your original code; what it show is that there's nothing wrong with it. How about jsfiddle.net/dTe73/1 ?
1

I found the source of the problem was that the parent div to which I was adding the dynamic div was not unique - there were multiple elements with same name ! This makes sense that it would fail. Thanks for everyones input.

Comments

-1

Replace $(newDiv).html(newHTML) with newDiv.html(newHTML)

and $('#dynDiv'+ID).append($(newDiv)) with $('#dynDiv'+ID).append(newDiv)

and it should work.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.