I need help. I have been assigned the task of grabbing a word out of a span element, and then assigning that word to the same span element as a class.
I have written this piece of code:
jQuery(".product span").each(function() {
if(jQuery("this:contains('hat')")) {
jQuery(this).addClass("hat");
} else if (jQuery("this:contains('sunglasses')")) {
jQuery(this).addClass("sunglasses");
} else {
jQuery(this).addClass("vest");
};
});
It does not work as it should however. It assigns the class 'hat' to all of the span elements within the class 'products'.
When using this:
jQuery(".product span").each(function() {
if(jQuery("this:contains('hat')")) {
jQuery(this).addClass("hat");
};
});
It works and assigns the class of 'hat' to the same span element. It also works if I do it this way. But I would prefer not to have three lines of code like this:
jQuery(".product span:contains('hat')").addClass("hat");
I want it in a nice if and else statement or another way that uses parsing if possible.
Other Note: I am not using jQuery's shortcut because it will collide with other library's I amusing. I also know of the var $js = jQuery.noConflict(); method.
A BIG BIG thanks to Sushanth, Kevin and Karl for the great response! I wish I could put both answers as the solution