0
<div class="parent">
    <div class="child"></div>
</div>

.child {
    background: red;
}

I have 5 parent divs with their child inside and each child has a different background color.

How I can get the child background color and reuse it as parent border color?

Note: Unfortunately, the childs background color is set and I cannot change it so I need some way to get it and reuse it for the parent.

Note: I am aware that with CSS only this is not possible so If someone can help me with JS or jQuery.

  • 1
    You can do it like this: https://codepen.io/Manoj6994/pen/wvJVaYE using [`window.getComputedStyle()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle) – m4n0 Jun 24 '21 at 13:04
  • `$(".parent").each((i, e) => $(e).find(">.child").each((ii, ee) => $(e).addClass(ee.className)));` https://jsfiddle.net/rmau49n8/ – freedomn-m Jun 24 '21 at 13:21
  • or the more common "go up" for css parent issues (ie select child then go up to parent rather than try to get children from parent) `$(".child").each((i,e) => $(e).closest(".parent").addClass(e.className));` https://jsfiddle.net/rmau49n8/1/ – freedomn-m Jun 24 '21 at 13:24
  • @m4n0 In the Codepen I do not see the parent inherit the background of the child. – Pembo Pechi Jun 25 '21 at 07:04
  • 1
    If you check the code. The background color is applied inline to the parent. Check the HTML. – m4n0 Jun 25 '21 at 07:19
  • @m4n0 no it is not and to see it just remove the child background colour and you will see that the background is gone. – Pembo Pechi Jun 25 '21 at 07:26
  • See? https://nimb.ws/AX1TZc – m4n0 Jun 25 '21 at 07:35
  • @m4n0 Sorry, maybe refresh was needed and now I see the parent background color. When I try to execute this script in the console I receive this "Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'." Any idea? – Pembo Pechi Jun 25 '21 at 08:20
  • 1
    Yes, because you need to access it using this code: https://nimb.ws/NwSIfB – m4n0 Jun 25 '21 at 08:52
  • @m4n0 everything is fine now, Thank you! – Pembo Pechi Jun 25 '21 at 09:18

0 Answers0