0

I have this code :

<div id="my-color-picker-1" class="color-picker jcolor-picker"> 
   <div data-type="btn" style="background: rgb(150,78,78)"></div>
</div>

I want to get this color : rgb(150,78,78);

I tried like this :

let x = document.getElementsByClassName("color-picker").firstChild;

But I have an undefined error.

Can you please give me some advices ?

Thx in advance.

GPiter
  • 779
  • 1
  • 11
  • 24

2 Answers2

2

1

You can also get the background using children property on the node Element also.

let elements = document.getElementsByClassName("color-picker");
const background = elements[0].children[0].style.background;
console.log( background );
<div id="my-color-picker-1" class="color-picker jcolor-picker"> 
   <div data-type="btn" style="background: rgb(150,78,78)"></div>
</div>

2

let element = document.getElementsByClassName("color-picker")[0]
const bgColor = element.firstElementChild.style.background;
console.log( bgColor );
<div id="my-color-picker-1" class="color-picker jcolor-picker"> 
   <div data-type="btn" style="background: rgb(150,78,78)"></div>
</div>
DecPK
  • 24,537
  • 6
  • 26
  • 42
0

firstChild will return you the node's first child in the tree.

Then you need nextSibling that returns the node immediately following the specified one in their parent's childNodes

let bgColor = document.querySelector("#my-color-picker-1").firstChild.nextSibling.style.backgroundColor

console.log(bgColor);
<div id="my-color-picker-1" class="color-picker jcolor-picker">
  <div data-type="btn" style="background: rgb(150,78,78)"></div>
</div>
Not A Bot
  • 2,474
  • 2
  • 16
  • 33