Reputation: 1
I tried to add a class to the following HTML code with jquery:
<img style="position: absolute; left: 0px; top: 0px; width: 37px; height: 94px; -moz-user-select: none; border: 0px none; padding: 0px; margin: 0px;" src="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png">
I tried doing this with this code and a few other ways but it did not work
<script>
$( 'img[src="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png"]' ).addClass("selected");
</script>
where is my error?
Upvotes: 0
Views: 2932
Reputation: 49
Try this:
$(document).ready(function(){
$('img[src*="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png"]').addClass('selected');
});
Hope that helps :)
Upvotes: 0
Reputation: 15795
You don't specify anywhere when you want this action to take place. Obviously you must wait for the document to load so the img will exist on the page before you add a class to it. this can be done by changing your script to:
<script>
$(document).ready(function(){
$('img[src$="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png"]').addClass("selected");
});
</script>
Notice that we are waiting for the document to be ready before we add the class to it.
Upvotes: 0
Reputation: 141
Try this:
<script>
$(function() {
$("img[src='http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png']").addClass("selected")
});
</script>
Upvotes: 0
Reputation: 13155
The problem is you are missed to add ready function :
Try this :
<script>
$(function(){ // ready function
$('img[src="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png"]').addClass("selected");
});
</script>
Your code :
<script>
$( 'img[src="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png"]' ).addClass("selected");
</script>
your code get executed before your image element loaded. Hence try putting you jquery code inside ready function.
Upvotes: 0
Reputation: 10350
The most easy way is to add an identifier to your image tag. This can be a class or ID:
<img id="mapfile-image" src="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png">
This way you can add your class by targeting the identifier:
$('#mapfile-image').addClass("selected");
Upvotes: 1