2

Is it possible to get all colorvalues that exist in a div with a certain class, and its child elements?

for example, i have:

<div class="row client">
<a href="somepage.php" style="color:#515151;">Link1</a>
<span style="color:#f3f3f3;">Span</span>
<h3 style="color:#ff00ff;">Subtitle</h3>
</div>

I want an array to get all colors:

background of the parent div
color of the <a> element
color of the <span> element
color of the <h3> element

Also, i'm using highcharts to display charts in the same div. Is it possible to get the colors used there aswell?

I don't think i can put this any clearer for you guys,

Many thanks!

Job

Ixbitz
  • 427
  • 1
  • 5
  • 7

3 Answers3

3

You can use:

var colorarray=[];
$('.client').children().addBack().each(function(){
  if(!$(this).is('.client'))
     colorarray.push("color of the <" +$(this).prop("tagName")+"> is "+ $(this).css('color'))
  else
     colorarray.push("background of <" +$(this).prop("tagName")+"> is "+ $(this).css('backgroundColor'))
})

Working Demo

If you want the color in hex, you can refer this https://stackoverflow.com/a/1740716/1719752

Community
  • 1
  • 1
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

You can just loop through all the elements in the div

Fiddle

var elements =  $(".client").children()

$(elements).each(function(index) {
  console.log( index + ": " + $(this).css("color"));
});
R4nc1d
  • 2,923
  • 3
  • 24
  • 44
  • Some advice on this: You're missing a semi-colon on the first line. Be consistent, either use one or don't. The `index` variable doesn't represent an index, it's an element, you should name it appropriately. `$(elements)` is not required, `elements` is already a jQuery object. – CodingIntrigue Apr 15 '15 at 07:44
  • 2
    couple of things. it is not considering parent tag, no tagname info is retrieved, – Milind Anantwar Apr 15 '15 at 07:48
0

Here’s a rather inefficient but, I think, easy to understand approach without libraries:

let allNodes = Array.from(document.querySelectorAll('*'));

let setOfColors = allNodes.reduce((colors,el) => {
  return colors.add(getComputedStyle(el).backgroundColor)
}, new Set)


let arrayOfColors = Array.from(setOfColors);