简体   繁体   中英

JQuery: How to add an id to a dynamically added element?

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.

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM