GPiter
GPiter

Reputation: 809

Get background color from the first child of a div

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.

Upvotes: 0

Views: 518

Answers (2)

DecPK
DecPK

Reputation: 25408

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>

Upvotes: 2

Not A Robot
Not A Robot

Reputation: 2694

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>

Upvotes: 0

Related Questions