Reputation: 104
I have a javascript which appends an element (a div) to my HTML page after the page is loaded. I would like to add an id to this dynamically div. How can i do that?
Here is more information : The first js is myscript1.js and is loaded at the bottom of the HTML page. In this script I have the following code :
$('div#existingDiv').append('<div class="newDiv">Content</div>');
The second js is myscript2.js and is loaded just after myscript1.js. I would like to add an Id.
$('div.newDiv').attr('id','div-1234');
But it seems that div.newDiv
does not exist.
I tried to get the children of div#existingDiv
(with $('div#existingDiv').children()
) but it returns an empty result.
Could someone help me?
PS : I can't modify the myscript1.js so please don't suggest me to do what I want to do in the myscript1.js file.
Upvotes: 0
Views: 135
Reputation: 232
your code seems to work. check it here: http://jsfiddle.net/2sL5T/ probably you problem is that
$('div.newDiv').attr('id','div-1234');
is executed before
$('div#existingDiv').append('<div class="newDiv">Content</div>');
first you need to find on what event your new html is inserted. is it happening on page load? then maybe you forgot to put your code in onload function? http://learn.jquery.com/using-jquery-core/document-ready/
Upvotes: 1
Reputation: 59232
You can do this:
$('#existingDiv div.newDiv:last').attr('id','div-1234');
This uses the fact that when you append something, it adds at the last.
Upvotes: 0