Identify specific elements using CSS to easily target them with JavaScript later on

Currently, I am utilizing CSS selectors to target specific elements and now I want to be able to identify those elements using javascript. My approach involves setting the color of these elements in css and then retrieving them based on their color. However, an issue arises as style.backgroundColor only returns the color if an inline style is applied.

To see my attempt in action, you can check out this demo here.

The CSS I used is as follows:

div{background-color: lightgrey;}

And for the JavaScript part:

alert(document.getElementById("myDiv").style.backgroundColor);

I am currently looking for a solution to make color detection work without relying on inline styles or maybe someone has a better suggestion on how to identify affected elements by CSS selectors. It's worth noting that I would like to avoid using jQuery for this task.

Answer №1

element.style is limited to returning inline style declarations or those added in JS using elements.style['foo'] = "bar". Keep in mind that CSS declarations with !important can override inline styles, and multiple CSS declarations may overwrite each other based on selector precedence rules.

To accurately determine the applied rule, use the getComputedStyle method: http://jsfiddle.net/qUDjb/31/

window.getComputedStyle(document.getElementById("myDiv"))['background-color']

MDN provides more information on getComputedStyle

If you aim to select elements by background color, consider obtaining a collection of elements and filtering them by computed style value: http://jsfiddle.net/qUDjb/36/

CSS

p:nth-child(2n) {
     background-color:lightgrey;
}

JS

var getElementsByBackgroundColor = function( collection, color ){
    // convert the color string to browser format
    var div = document.createElement('div');
        div.style.backgroundColor = color;
    var computedColor = div.style.backgroundColor;

    // compare computed background color and return matching elements
    return [].slice.call( collection ).filter( function( item ){
       return window.getComputedStyle( item )['background-color'] == computedColor;
    });
}
console.log( getElementsByBackgroundColor( document.querySelectorAll('p'), 'lightgrey') );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The content within the mat-card-content paragraph exceeds the boundaries of the mat-card container,

I recently began working with Angular Material and came across an issue. When I have a shorter text paragraph, it overflows the card. However, when I use a larger paragraph, the text wraps nicely. Here is the code snippet: <mat-card *ngFor="let s ...

a dedicated TypeScript interface for a particular JSON schema

I am pondering, how can I generate a TypeScript interface for JSON data like this: "Cities": { "NY": ["New York", [8000, 134]], "LA": ["Los Angeles", [4000, 97]], } I'm uncertain about how to handle these nested arrays and u ...

Exploring the powerful capabilities of utilizing state variables within styled components

I'm attempting to create a button that changes its state based on the value of a property within an object. Below is the styled component const Btn = styled.button` border-radius: ${props => props.theme.radius}; padding:5px 10px; backgroun ...

What is the best way to anticipate a return phone call?

Looking to retrieve the largest date from a folder by reading its contents. https://i.stack.imgur.com/KYren.png Here is the code snippet to read the folder, extract filenames, and determine the largest date (excluding today): async function getLastDate ...

Writing the success function for a jQuery ajax call involves defining the actions to be taken once

Embarking on my journey to learn jQuery and web development, I am faced with the task of sending user input (username and password through a submit button) to a PHP page using .ajax and success function. Below is the HTML form code: <form id="form1"&g ...

What is the best way to transition a connected component from a class-based to a functional component in TypeScript?

I'm in the process of switching from a class-based component to a functional component. This is a connected component that uses mapState. Here is my initial setup: import { connect } from 'react-redux' import { fetchArticles } from '. ...

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

Combining object IDs with identical values to create a new array in JavaScript

i have an array of objects that are a join between the transaction, product, and user tables. I want to merge IDs with the same value so that it can display two different sets of data in one object. Here's my data let test = [ { Transac ...

Issue encountered with AJAX request using JavaScript and Express

I'm brand new to this and have been searching online for a solution, but I can't seem to figure it out. It's possible that I'm making a basic mistake, so any assistance would be greatly appreciated. I'm trying to create a simple f ...

Error message: Unauthorized request error with the change.org JavaScript API

I am currently working on integrating the javascript API from change.org in order to retrieve all of my signed petitions for display on my source forge page. However, I am encountering an unauthorized request response from the change.org API. Despite tryi ...

Enhanced Custom Code Highlighting for Aptana Studio 3 with support for .less files

Looking to enhance syntax highlighting for .less files in Aptana Studio 3 but struggling to find a solution. XText only works with Eclipse, and the forums offer limited guidance. Has anyone successfully implemented custom syntax highlighting for .less fi ...

Updating charts in React using Chart.js with the click of a button

I am currently learning React and Chart JS, but I have encountered an issue. I am unable to change the data by clicking on a button. Initially, the graph displays: var Datas = [65, 59, 80, 81, 56, 55, 69]; However, I want to update this graph by simply p ...

Unique column arrangement specifically designed for the initial row within the loop

My webpage features a layout that showcases 4 images on each row. However, I am looking to create a special first row with a unique column configuration compared to the rest of the rows. Here is an example of what I have in mind: This particular row will ...

(CSS) Unusual phantom white outline surrounding menu with no visible border

I've just finished creating my first multi-level drop-down menu, but I'm encountering two white border issues. The first white border appears at the bottom of the menu and seems to be related to the padding of the a-elements. The specific area in ...

What is the best method for converting a list tag into an array of objects with XPath?

I am attempting to extract the ordered list and generate an array of list tags along with their content. I have experimented with different paths, such as: //li[div/@class="business-info"] //li[div[@class="business-info"]] //li[descendant::div[@class="bu ...

Pictures do not adhere to the maximum width set on their parent elements

When the max-width CSS style is set on the body tag and an image within the body surpasses this maximum width, the image does not adhere to the set limit. Instead of resizing, it simply overflows. Why does this happen? So, what is the solution to this pro ...

Exploring Nested Routes and Queries in Vue JS

As a beginner in Vue, I have been exploring a demo project and struggling with understanding how routes with query parameters function. The documentation suggests using router.push({ path: 'register', query: { plan: 'private' }}) to gen ...

When I use the jQuery foreach loop, I notice that it produces identical results for both values

Hey there, I'm encountering a new issue with this jQuery script. In my foreach loop, I am extracting the product names and descriptions. The problem arises when I have 2 distinct products with different descriptions, but the following code: <d ...

The table appears to be fixed in place and will not scroll, even though the data

Previously, my code was functioning perfectly with the mCustomScrollbar I implemented to scroll both vertically and horizontally on my table. However, while revising my jQuery code for organization purposes, I seem to have unknowingly altered something tha ...

Can you explain the distinction between escapeXml and escapeHtml functions?

When it comes to escaping characters in JSP pages, I am wondering which is the better option - using escapeXml or escapeHtml? ...