tags:

views:

27

answers:

2

How do you replace an attribute within a specific tag in a known class/id?

example, replace the src in img with a different file:

<div class="apple" id="poisoned">
<img border="0" width="25" height="25" src="default.png"></div>

But there are also other elements with the same id...

<div class="pear" id="poisoned"><img border="0" width="25" height="25" src="default.png"></div>

Suppose you just want to update the image in apple, how do you select it using jQuery?

Here's my try so far (*Edit - works)

$(".apple[id=poisoned] img").attr('src','replaced.png'); // not working
  • Edit - There are multiple apples and pears and other fruits on the page... Each poisoned fruit acts similarly, though not all should be poisoned at the same time! (Multiple will eventually be poisoned as they're clicked...) There is only one poisoned fruit per fruit type! (e.g. only 1 poisoned apple, only 1 poisoned pear, etc.)
  • Edit 2 - Actually, my try above works... Code error was in something else >.>
+2  A: 

If I'm understanding you correctly,

$('#poisoned img').attr('src', 'newimage.png');

If you'd prefer to select by class,

$('.apple img').attr('src', 'newimage.png');

but I think you have your class and ID confused. IDs are supposed to always unique, whereas classes are not; you seem to be implementing them the other way around.

Also, please work on your 20% accept rate :)

Matchu
slightly more complicated (edited above for clarity, sry!) - what if there are multiple instances of the same class?
ina
@ina - IDs should *always* be unique, by definition. If it's not unique, it needs to be a class, instead.
Matchu
hm, how would you redefine the class/id in this case?
ina
@ina - probably swap them. You seem to be using classes as unique and IDs as groups, whereas the reverse is how they are intended (and, therefore, how browsers are optimized to treat them).
Matchu
OK - edited again.. Problem is there are several apple's, pear's and other fruits on the page. There is only one poisoned "id" for each type of fruit... I've been able to get by with $(".apple[id=poisoned]") so far, but not with replacing a specific attribute in a tag within the div (see above).
ina
@ina - in that case, `apple`, `pear`, and `poisoned` all define groups of sorts, so should all be classes.
Matchu
eek.. mea culpa! ;-)
ina
A: 

Something like:

$("div#poisoned img").attr('src','newimage.png')
Matthew Manela