alQemist
alQemist

Reputation: 360

jQuery adding element to dynamic element

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 ??

Upvotes: 2

Views: 2000

Answers (3)

alQemist
alQemist

Reputation: 360

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.

Upvotes: 1

blgt
blgt

Reputation: 8215

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

Upvotes: 1

Razzildinho
Razzildinho

Reputation: 2584

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

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

and it should work.

Upvotes: -1

Related Questions