Reputation: 9
I want do something if all elements with same css class have the same css property value.
Here's my attempt which doesn't work:
$('.element-item').each(function() {
if( $(".element-item").css('background') = '#ccc') {
// do something
}
});
Upvotes: 1
Views: 209
Reputation: 8181
You cannot access compound properties like that. If you are really interested in the color, and it's not just an example, you'll have to use background-color
. Also, the value returned will be rgb
so you are going to need a little math.
As I understand, you want your function to run once only if all elements in the collection pass the check, so you can't use an each
loop because it will run for each element that matches the condition.
You can filter the elements for the property that you are interested in and check if the two collections contain the same number of items.
checkItems(".element-item");
checkItems(".element-item2");
function checkItems(selector) {
$items = $(selector);
$ccc = $items.filter(function() {
return ($(this).css('background-color') == 'rgb(204, 204, 204)');
});
if ($items.length == $ccc.length) {
// Same number of elements, run the function
console.log(selector + " passes the test");
} else {
console.log(selector + " doesn't pass the test");
}
}
.element-item,
.element-item2 {
background: #ccc;
}
#black {
background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element-item"></div>
<div class="element-item"></div>
<div class="element-item"></div>
<div class="element-item2"></div>
<div class="element-item2"></div>
<div class="element-item2" id="black"></div>
Upvotes: 0
Reputation: 17288
In javascript ==
is the operator to compare values. Using a single '=' assignment operator will result in a ReferenceError
(due to invalid assignment) which stops processing of your "do-something" block of code.
$('.element-item').each(function() {
if( $(".element-item").css('background') == '#ccc') {
// do something
}
});
Upvotes: 1
Reputation: 2104
You can check all selectors by below code:
$('.element-item').each(function() {
if( $(this).css('background') == '#ccc') {
// do something
}
});
Hope it helps you!!
Upvotes: 1