I have a strange problem. I have used this before with no problems, but all of a sudden it doesn’t work at all. I’m trying to get the id value of an element:
<script>
$(document).ready(function() {
$("img").live('click', function(event) {
var name = $(this).text();
var id = $(this).attr('id');
var id = this.id;
alert(id);
event.preventDefault();
});
});
</script>
Here’s the element:
<img src="<?=base_url()?>assets/images/test.jpg" id="myId"/>
I have tried the alert with both the variants above, with this.id directly and via the attr function. Neither works. $(this).text() works fine.
I get “undefined” in the alert box…
What is going on?
As you can see from this example your code works perfectly: http://jsfiddle.net/nicolapeluchetti/VwzZm/ so the error must be elsewhere.
In fact text() does this:
And so it’s very unlikely that it gets your id.