Marian07
Marian07

Reputation: 2580

Can't access element using its new id

i am triyng to acces an elemet using its new atribute.

HTML

<div class="element">Element1</div>

The script is

$('.element').one("click", function() 
{
    $.getScript('/script.js');
});  

$('#activated').click(function() 
{
    alert(1);
});

Inside the script.js file :

$('.element').attr("id", "activated");

The script.js adds the id #activated to the div, but .click() won't work using the new id.

Can someone please tell me why?

Upvotes: 1

Views: 128

Answers (3)

Ram
Ram

Reputation: 144699

When the line $('#activated').click(function() is executed, there is no element with ID of activated in the document, so jQuery returns an empty collection and click method silently fails. You can either use the event delegation technique:

$(document).on('click', '#activated', function() 

or check the id of the clicked element in your first event handler:

$('.element').on("click", function() 
{
    if ( this.id === 'activated' ) 
    {
       // ...
    } 
    else 
    {
       $.getScript('/script.js');
    }
}); 

Upvotes: 1

Meer
Meer

Reputation: 1026

try $(document).on('click','#activated',function(){ // do somthing here }); it might work. Tell me it doesnt.

Upvotes: 0

Macil
Macil

Reputation: 3703

$('#activated') is evaluated before any element has that id, so it finds no elements, and no click handlers are attached to any elements.

You can use event delegation to work around this. A click handler will be attached to the document body immediately, but it will only trigger its callback if the target element matches the '#activated' selector:

$(document.body).on('click', '#activated', function() 
{
    alert(1);
});

Upvotes: 4

Related Questions