Sylar Sylar - 4 months ago 8
CSS Question

How to apply style to the correct tag with JQuery

I'm trying to add more logic to my code but it's not working. I have to wrap my icon around a

span
tag so I get the line height properly. I'm using google font:

html.erb

<!-- inside a loop -->
<span class="wish-flex cursor" data-id="wish">
<i class="material-icons cursor">favorite_border</i> Add Wishlist
</span>
<input type="hidden" class="wish-cls" value="<%= product.id %>" />


SCSS

...

span.wish-flex{
display: inline-flex;
vertical-align: middle;
padding-top: 10px
}

.material-icons.red { color: $hotRed; }

span .material-icons{
margin-top: -2px
}


JavaScript

$("[data-id=wish]").click(function(e){
e.preventDefault();

var value = $(this).next(".wish-cls").val();

console.log("Clicked: " + value);

/* Applying the css when clicked
*
* We use toggleClass instead of addClass
* TODO: Ajax
*/
$(this).toggleClass("red");

});


The code is applying the class
red
to the span. Correct but how to get it to apply the
class
to the
i
tag? If the user clicks the heart or the word (Add Wishlist), the script runs.

Maybe I could change up the
css
to get the inline style with the icon and the text and remove the
span
?

Answer

In your case the this inside of the event handler will point to the span element, But what you are trying to select is the i element inside of it. So you have to use either find() or children() to be invoked from $(this) to get it.

$("[data-id='wish']").click(function(e){
  e.preventDefault();
  var value = $(this).next(".wish-cls").val();
  $("i", this).toggleClass("red");
});

This signature $("selector", elem) is similar to $(elem).find("selector").