Reputation: 22490
please have a look at following question and answer, the seccond answer (with the many upvotes) Jquery: How to check if the element has certain css class/style
looks like this:
if ($('#yourElement').css('position') == 'absolute') {
// true
}
so this is awesome but I would like something like
if ($('#yourElement').css('position') == 'absolute') {
$(this).addClass('xxx');
}
so the element with the ID "yourElement" gets a class added
what is the easyest way to do that
Upvotes: 0
Views: 2457
Reputation: 20230
Assign $('#yourElement')
to a variable. Then perform the check on that variable and add the class to it as well. This simply saves on the number of queries made to the DOM with the $()
function in your example and in the likely possibility that further manipulation is required.
For example:
var your_element = $('#yourElement');
if (your_element.css('position') == 'absolute') { your_element.addClass('xxx'); }
Upvotes: 2
Reputation: 38345
You could do it this way:
$('#yourElement').addClass(function(index, currentClass) {
return $(this).css('position') == 'absolute' ? 'xxx' : '';
});
For more information on the syntax take a look at the API for .addClass()
.
Upvotes: 4
Reputation: 73976
// Cache your element first
var $element = $('#yourElement');
if ($element.css('position') == 'absolute') {
$element.addClass('xxx');
}
Upvotes: 2
Reputation: 101
var yourElement = $('#yourElement');
if (yourElement.css('position') == 'absolute') {
yourElement.addClass('xxx');
}
Upvotes: 2