tags:

views:

35

answers:

2

I have a generated HTML file which has large blocks of text with span's sprinkled throughout it with generated class names:

This <span class="21232">an example</span> of what <span class="332423">
I'm talking</span> about.  There are span's with <span class="21232"> generated
ID's </span>.

Now, what I'm seeking to do, is if I hover over any of my spans, they will add a border to not only that span, but all other spans that share that same class.

So, if I were to hover over the first span, it would wrap a border around "an example" and "generated ID's" because the first and third span share the same class name.

I was pretty sure I couldn't do it in straight CSS. Is this possible using jQuery? If so, can anyone point me in the right direction for doing this as simply as possible?

+3  A: 
$('p#experiment > span[class]').hover(function(){
    $('.' + $(this).attr('class')).css('border', '1px solid red')
},
function(){ 
    $('.' + $(this).attr('class')).css('border', 'none') 
})

http://jsfiddle.net/RE3ya/1/

meo
@meo: I think numbers are valid class names. Far as I know, it is just about 'anything goes' for classes (primary exception being spaces, as they are separators).
patrick dw
it is better to use the `.` notation for the classes when selecting them with jquery, instead of the `class=..` because it will work even if there are more than one classed defined for that element..
Gaby
your right, this just count for ID's i ahve corrected my awnser
meo
@gaby thx for this! +1 i have adapted my example and the jsfiddle link
meo
+2  A: 
$('span[class]').hover(
function() {
    $('.' + $(this).attr('class')).css('border','1px solid purple');
},
function() {
    $('.' + $(this).attr('class')).css('border','');
}
)
patrick dw
come on leave me some points :P but +1 for the span[class]
meo
i think it would be better to add/remove a class that has the border rule set.. so that the border returns to its original values after the hover..
Gaby
@Gaby: I agree that it is better to add/remove classes rather than have styles spread out in js, but this does clear out the set value. Or am I missing what you meant?
patrick dw
i mean that if a different border was set by the existing rule(before the hover), it would be lost when you set it manually to the empty value (after the hover) ..
Gaby
@Gaby: OK, I get your point. I don't think it's an issue here, as the spans seem to exist solely for the purpose of highlighting when hovering, but in general, I'd agree that classes would be safer if there's any uncertainty.
patrick dw
yes, you are right ... my comment was more as a general rule .. the specific use here is as you describe.
Gaby