开发者

Jquery, after cloning and changing id of a div, cannot access the element through that id

开发者 https://www.devze.com 2023-04-07 08:59 出处:网络
After I clone my (div) container and change the id, I cannot seem to get at it using the id-selector, am I doing something wrong? I know the clone is correct, I know the id changed good, but I can no

After I clone my (div) container and change the id, I cannot seem to get at it using the id-selector, am I doing something wrong? I know the clone is correct, I know the id changed good, but I can no longer use the default Jquery selector to get at that element.

var clone = $('#test').clone(); 
clone.attr('id', 'abc');

alert(clone.attr('id')); // gives 'abc'
alert($("#abc").html()); // g开发者_如何学编程ives null   <------------ WHY?
alert(clone.html());     // gives correct html


You haven't inserted the clone into the DOM yet. This $("#abc") looks in the current document for that ID and it isn't in there yet.

This works:

var clone = $('#test').clone(); 
clone.attr('id', 'abc');

alert(clone.attr('id'));            // gives 'abc'
$(document.body).append(clone);     // <==== Put the clone into the document
alert($("#abc").html());            // gives correct html
0

精彩评论

暂无评论...
验证码 换一张
取 消