Can one access a child node and retrieve its inherited background color?

During my initial testing in jsFiddle, I encountered the following scenario: https://jsfiddle.net/6pqxfy2o/

$(function(){
console.log("fired");
  $("div").each(function(){
  console.log($(this).attr("class"));
    console.log($(this).css("background-color"))})
})
.color{
  background-color:teal;
}

.dim{
  width: 200px;
  height: 200px;
}

.sub-dim{
  width: 50px;
  height:50px;
  border: solid 1px white;
}
.ping {
  background-color: cyan;
}

.ack {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dim color">
  <div class="sub-dim ack">
  
  </div>
  <div class="sub-dim ping">
  
  </div>
  <div class="sub-dim">
  
  </div>
</div>

In testing, it became apparent that the inherited color was not being passed down to the children when the code was executed.

I am interested in finding out how to determine the background color of a sub-dim element that does not have its own background color, either by identifying the current color or by accessing the nearest one.

Ultimately, when iterating through sub-dim elements, I would like to retrieve [red, cyan, teal] or their respective color codes. In the provided example, the inner div is transparent, allowing the parent's color to show through.

Answer №1

To easily get the new computed color of a transparent element, simply set it to inherit.

// Determine the actual value of "transparent" in different browsers
var transparent = (function() {
  var backup = document.body.style.backgroundColor;
  document.body.style.backgroundColor = 'transparent';
  var bg = getComputedStyle(document.body).backgroundColor;
  document.body.style.backgroundColor = backup;
  return bg;
})();
[].forEach.call(document.getElementsByTagName("div"), function(el) {
  var bg = getComputedStyle(el).backgroundColor;
  if (bg === transparent) {
    var backup = el.style.backgroundColor;
    el.style.backgroundColor = 'inherit';
    bg = getComputedStyle(el).backgroundColor;
    el.style.backgroundColor = backup;
  }
  console.log(el.className, ":", bg);
});
.color {
  background-color: teal;
}
.dim {
  width: 200px;
  height: 200px;
}
.sub-dim {
  width: 50px;
  height: 50px;
  border: solid 1px white;
}
.ping {
  background-color: cyan;
}
.ack {
  background-color: red;
}
<div class="dim color">
  <div class="sub-dim ack"></div>
  <div class="sub-dim ping"></div>
  <div class="sub-dim"></div>
</div>

Answer №2

Although I may not have a complete grasp of the issue at hand, one possible solution could be to experiment with

.sub-dim.ack {
  background-color: red;
}

or

.ack, .ack * {
  background-color: red;
}

It would be beneficial to specify the child elements you want to target for better results.

Using SASS might provide a more streamlined approach to this problem.

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

Program that extracts information from interactive controls

One of my challenges involves working with pages that have dynamic controls, where I never know the types or quantities of controls present. My goal is to create a script that can extract text from a text area when it's clicked. Although I initially b ...

Containers situated at the core

Seeking assistance with centering two containers horizontally on the site. Specifically, I would like the menu with the logo on the right side and the content block to be centered. Despite trying various methods, nothing seems to work for me. Previously, I ...

In Angular, when a component is clicked, it is selecting entire arrays instead of just a single item at a

I am currently working on implementing a rating feature using Angular. This component will be used to rate different languages based on how proficient I am with them. My issue lies in the fact that when I click on one array element, it automatically selec ...

Unable to arrange an array of JavaScript objects retrieved via an Angular REST request

I'm currently encountering an unusual issue with sorting an array of JavaScript objects. While sorting some dummy data works fine, I am unable to sort the array when fetching the object through an Angular REST call. The structure of the message is as ...

CSS - Creating a stylish break line for link boxes

Struggling with creating a box that includes linked text and a line break. However, the issue arises when the line breaks, causing the box to also break. After trying multiple options, I still can't seem to find a solution. Check out my attempt her ...

manage user assignments for multiple events in Django

Struggling to create a method for admin users to assign multiple events to users within the event details. The goal is to allow users to be associated with many events, and events to have multiple users linked to them. Unfortunately, I haven't been ab ...

Avoid the button being clicked more than once

As a newcomer to JavaScript and AngularJS, I recently created a demo showcasing simple page navigation with modals. However, I encountered an issue where clicking on a button twice resulted in opening the same page twice. Despite using a timeout function i ...

Maintain the selected list item after filtering in AngularJS

I am facing an issue with highlighting selected items in a list. I have three first names: Roy, Sam, David displayed in a ul as list items. Initially, I can toggle each li on click just fine. However, after performing a search and returning to the list, th ...

A Guide to Parsing JSON Data in JavaScript

I am facing an issue with the JSON received from an AJAX call. The problem lies in the unexpected '\t' after a bullet point, causing a JavaScript error in the JSON.Parse(data.d) function. Can you provide advice on how to address this situati ...

Troubleshooting the issue with nodejs fs createWriteStream and file path prefixes

My goal is to call an API, iterate through an array of images, assign unique names to each image in the array, and then save them to a local directory. By simplifying the code, I can achieve this by writing them to the root folder. The sub folder was alrea ...

Despite passing JSLint, an unexpected end of input still occurred

It seems a bit absurd; despite my efforts, I'm unable to locate the syntax error. The Chrome debugger keeps indicating an "unexpected end of input" in line two. Any suggestions? $("head meta").each(function () { var content = JSON.parse(this.cont ...

Having issues with my JavaScript code - it just won't function

I am having an issue with my JavaScript code. I don't receive any errors, but when I click the submit button, nothing happens. I have followed a video tutorial and watched it twice, but I can't seem to figure out what is wrong here. Here is the ...

retrieving the html select element located within a table td

My code snippet consists of the following HTML elements: <table> <tr> <td><select name="day"> </select></td> <td><select name="time"> </select></td> &l ...

I'm currently working on setting up my registration website, however, I've encountered an error in the terminal

I encountered an error message stating: TypeError: Object of type builtin_function_or_method is not JSON serializable Can someone explain the meaning of this message to me? ...

Using NgTable to sort and filter selections

I am working with two select elements. The first select is populated with names, and I would like the second select to only display the ages corresponding to the selected name. For example: If I select Jacob in the first select, I want the Age select to ...

The camera completes seven full rotations around its axis using THREE.JS and GSAP

I'm currently working on an online gallery and I am having trouble with the camera movement when scrolling. Whenever I try to rotate it along the Y axis, it ends up rotating three times around its axis which is not the desired behavior! I am trying ...

Unleashing the power of TypeScript with Solid JS Abstract Class

Why am I getting an undefined error for my calcUtilisation method when using an Abstract Class as the type in createStore? Is there a way to utilize a type for the data along with a method within the same class for createStore? abstract class Account { ...

In Electron, methods for detecting and resolving Error TS2304: Unable to locate the name 'unknown on(event: 'ready', listener: (launchInfo: unknown) => void): this are essential for smooth operation

Encountering an issue while running npm build. Electron version: 7.1.2 TypeScript version: ^2.5.1 Target version: ES2017 Here are the details of the error. When I performed the build under the following conditions: Electron version: 6.0.0 TypeScript ver ...

Using jquery to refresh several backgrounds at once

While I have some knowledge of CSS and various JavaScript libraries, I've encountered difficulty in integrating multiple backgrounds into the code that I found on this link: http://codepen.io/quasimondo/pen/lDdrF. My goal was to overlay a transparent ...

Tips for Arranging HTML Elements Next to Each Other with CSS3

As a beginner in programming, I am embarking on the task of creating a basic website inspired by a dribble design. I am currently struggling to align an image and text side by side within a section, so that they stack on top of each other when the screen ...