Reputation: 500
Using jQuery, how would I go about changing the style of the <span>
element, when the image is hovered in each post?
Here is an example of the HTML structure:
<img src="#" class="postone">
<div class="description">
<p><span class="postone"> text </span> other text </p>
</div>
<img src="#" class="posttwo">
<div class="description">
<p><span class="posttwo"> text </span> other text </p>
</div>
Here is the jQuery I have already:
$(document).ready( function(){
$("img").hover( function(){
var className = $("this").attr('class');
$("span" + className).css("color", "#fff");
});
});
Upvotes: 0
Views: 238
Reputation: 5211
$(document).ready(function() {
var className;
$("img").hover(function() {
className = $(this).attr('class');
$("span." + className).css("color", "#fff");
}, function() {
className = $(this).attr('class');
$("span." + className).css("color", "#000");
});
});
You are missing a .
in your class selector, and you also need to remove the double quotes from $(this)
. Add a mouseout function also in your code.
Upvotes: 2
Reputation: 723598
Two issues:
this
is a keyword, not a string, so the quotes should be removed.
var className = $(this).attr('class');
You're missing a period in your selector. The className
value does not contain this period since the class
attribute contains class names, not class selectors, so you will have to put it in the selector string yourself.
$("span." + className).css("color", "#fff");
With that said, I really don't see why you couldn't do this with CSS:
img:hover + .description span {
color: #fff;
}
Upvotes: 3