To check if an element has a certain CSS style in JavaScript, you typically use window.getComputedStyle()
for the most accurate applied style, element.style
for inline styles, or the css()
method if you are using jQuery.
Here's a breakdown of how to accomplish this effectively:
How to Check if an Element Has a Certain CSS Style in JavaScript
Detecting an element's CSS properties is a common task in web development, crucial for dynamic styling, layout adjustments, and interactive user experiences. JavaScript provides robust methods to query both the directly applied inline styles and the final computed styles that render on the page.
1. Checking Computed Styles with Pure JavaScript (window.getComputedStyle()
)
The most reliable way to determine the final, applied style of an element (as rendered by the browser) is by using window.getComputedStyle()
. This method returns a read-only CSSStyleDeclaration
object that contains all the CSS properties and their values for the specified element, after applying all active stylesheets and resolving any conflicts.
When to use it:
- You need to know the actual style an element is displaying, regardless of whether it comes from an inline style, an internal stylesheet, an external stylesheet, or user agent styles.
- You are checking for styles that might be inherited or overridden by other rules.
Syntax:
const element = document.getElementById('myElement');
const computedStyle = window.getComputedStyle(element);
const propertyValue = computedStyle.getPropertyValue('property-name'); // or computedStyle.propertyName
Example:
Let's say you have an HTML element:
<div id="myBox" style="padding: 10px;">Hello World</div>
<style>
#myBox {
background-color: blue;
color: white;
font-size: 16px;
}
</style>
To check its color
and background-color
:
const myBox = document.getElementById('myBox');
const computedStyle = window.getComputedStyle(myBox);
// Check background color
if (computedStyle.backgroundColor === 'rgb(0, 0, 255)') {
console.log('The box has a blue background.');
} else {
console.log('The box does not have a blue background.');
}
// Check font size
if (computedStyle.fontSize === '16px') {
console.log('The font size is 16px.');
} else {
console.log('The font size is not 16px.');
}
// You can also use getPropertyValue for dashed properties
const paddingValue = computedStyle.getPropertyValue('padding-top');
console.log(`The top padding is: ${paddingValue}`); // Outputs '10px'
For more details, refer to the MDN Web Docs on window.getComputedStyle().
2. Checking Inline Styles with Pure JavaScript (element.style
)
The element.style
property allows you to access and manipulate styles defined directly within an element's style
attribute. It only reflects styles explicitly set as inline, not those applied via stylesheets or inherited properties.
When to use it:
- You need to check or modify a style that was directly set on the element using its
style
attribute. - You are working with styles dynamically applied via JavaScript using
element.style.propertyName = 'value';
.
Syntax:
const element = document.getElementById('myElement');
const inlineValue = element.style.propertyName;
Example:
Consider the same HTML:
<div id="myBox" style="padding: 10px; color: green;">Hello World</div>
<style>
#myBox {
background-color: blue;
}
</style>
To check its inline color
and background-color
:
const myBox = document.getElementById('myBox');
// Check inline color
if (myBox.style.color === 'green') {
console.log('The inline color is green.');
} else {
console.log('The inline color is not green.');
}
// Check inline background color (will be empty because it's from a stylesheet)
if (myBox.style.backgroundColor === '') {
console.log('No inline background color is set.');
}
For more information, visit the MDN Web Docs on HTMLElement.style.
3. Checking Styles with jQuery (The css()
Method)
If you are working with the jQuery library, it offers a very convenient css()
method to check if an element contains certain CSS styles or not. This method simplifies the process of retrieving computed style properties. When used to get a style property (i.e., with one argument), jQuery's css()
method generally returns the computed style, similar to window.getComputedStyle()
.
When to use it:
- You are already using jQuery in your project.
- You want a concise way to retrieve an element's computed style.
Syntax:
const propertyValue = $(selector).css('property-name');
Example:
Assuming jQuery is loaded, with the same HTML:
<div id="myBox" style="padding: 10px;">Hello World</div>
<style>
#myBox {
background-color: blue;
color: white;
}
</style>
To check its color
and background-color
using jQuery:
$(document).ready(function() {
const $myBox = $('#myBox');
// Check background color
if ($myBox.css('background-color') === 'rgb(0, 0, 255)') {
console.log('The box has a blue background using jQuery.');
}
// Check padding
if ($myBox.css('padding-top') === '10px') {
console.log('The box has 10px top padding using jQuery.');
}
});
For further details on jQuery's css()
method, refer to the jQuery API Documentation.
4. Checking for Specific CSS Classes (element.classList.contains()
)
Sometimes, the intent is not to check the value of a style property, but rather if an element has a specific class that would apply certain styles. This is a different approach but relevant if your styling is primarily class-based.
When to use it:
- You want to know if an element has a particular CSS class assigned to it.
- You manage styles by toggling classes rather than directly manipulating
style
properties.
Syntax:
const hasClass = element.classList.contains('class-name');
Example:
HTML:
<div id="myElement" class="active highlight">Click Me</div>
JavaScript:
const myElement = document.getElementById('myElement');
if (myElement.classList.contains('active')) {
console.log('The element has the "active" class.');
}
if (!myElement.classList.contains('inactive')) {
console.log('The element does not have the "inactive" class.');
}
For more information, see the MDN Web Docs on Element.classList.
Comparison of Methods
Method | Checks | Use Case | Best For |
---|---|---|---|
window.getComputedStyle() |
Final, rendered style (computed value) | Determining the actual visual style of an element | Most accurate style value, regardless of source |
element.style |
Inline styles (style attribute) |
Checking or modifying styles set directly on the element | Styles set directly via style="" or JavaScript |
$(selector).css() (jQuery) |
Final, rendered style (computed value) | Conveniently retrieving computed styles in a jQuery project | Simplicity when using jQuery |
element.classList.contains() |
Presence of a specific CSS class | Checking if an element has a class that implies certain styling | Class-based styling logic |
Practical Considerations
- Property Names: When using
getComputedStyle
orelement.style
, use camelCase for CSS properties (e.g.,backgroundColor
instead ofbackground-color
). When usinggetPropertyValue()
or jQuery'scss()
, you can use either camelCase or kebab-case (e.g.,'background-color'
or'backgroundColor'
). - Returned Values:
getComputedStyle
returns absolute pixel values for dimensions and positions, andrgb()
orrgba()
values for colors, even if they were originally defined using hex or named colors. Be prepared to compare against these formats. - Performance: For simple checks, performance differences are negligible. For highly repetitive checks in performance-critical applications,
element.style
might be slightly faster as it avoids the overhead of computing all styles, but it's often not the correct value you need.getComputedStyle
is generally optimized by browsers.
By choosing the appropriate method, you can accurately query and react to the CSS styling of your web elements.