tags:

views:

24

answers:

5

Hi everybody,

I've a problem to get the id of dynamically loaded anchor appended to a div. Here is the code that I get after filling the div:

<div id="sotto_eti">
    <a href="#" id="a">a</a> <a href="#" id="b">b</a> <a href="#" id="c">c</a>
</div>

and here is the script:

<script>
$("#sotto_eti a").click(function()
{
    alert($(this).attr("id"));
});
</script>

Thanks in advance for your help

ciao h.

A: 
    alert($(this).get(0).id);

should work.

Nik
This doesn't really fix the issue. Using `$(this).attr("id")` is correct. Your version wraps `this` with jQuery, then immediately removes it and accesses the `id` property. So it would make *much* more sense to do `this.id`.
patrick dw
A: 

You need to use live method for dynamic elements:

$("#sotto_eti a").live('click', function()
{
  alert($(this).attr("id"));
});

Here is working demo

Also make sure that you include the jquery library in your page.

Sarfraz
No need to wrap your code with `.ready()` if you're using `.live()`. http://jsbin.com/agigu3/2/ :o)
patrick dw
@patrick dw: That's interesting, i will update. thanks :)
Sarfraz
I've not write but I already use ready handler but it does not works :(
haltman
@haltman: You need to use `live` for dynamic elements :)
Sarfraz
A: 

Use live() for elements added later:

Dr.Molle
+2  A: 

You can use .live() to handle dynamically loaded elements:

$("#sotto_eti a").live('click', function() {
    alert( this.id );
});

Or better, use .delegate() which is similar to .live(), but more efficient.

$(function() {
    $("#sotto_eti").delegate('a', 'click', function() {
        alert( this.id );
    });
});
patrick dw
`more efficient` do you have any source for that?
Rakesh Juyal
@Rakesh - Simply based on the fact that they do the same thing, but `.delegate()` is localized. When you do `.live()`, jQuery needs to test *every* click on the page that bubbles up to the root against the `"#sotto_eti a"` selector. With `.delegate()`, only clicks *inside* the `"#sotto_eti"` container need to be tested against the `"a"` selector. Also, because there can be only one `#sotto_eti` on the page, there's only *one* handler in both cases, so there's no extra overhead with jQuery managing multiple handlers.
patrick dw
ohk :) so here goes my +1
Rakesh Juyal
+1  A: 

Hi,

if you would retrieve the ID of a links added dynamically, you should use the live function instead :

<script>
$("#sotto_eti a").live("click", function()
{
    alert($(this).attr("id"));
});
</script>
Arnaud F.