Home > Back-end >  JS - Copy colour value to another element
JS - Copy colour value to another element

Time:01-24

I'm trying to copy the color value from the <h1> element to a <path> element. However when I try to achieve this with document.querySelectorAll() it doesn't work but it works with document.getElementById()

mycolor_element = document.querySelectorAll('#my_id h1')[0]; 
let my_value = window.getComputedStyle(mycolor_element).color;
document.querySelectorAll('#my_element svg path')[0].style.fill = my_value;

I expect that if my <h1> is orange then my <path> is also orange.

CodePudding user response:

You can use querySelector (if is just one element) with window.getComputedStyle for catch color of element then set it to the svg like:

const mycolor_element = window.getComputedStyle(document.querySelector('#my_id')).color;
document.querySelector('#my_element > svg > circle').style.fill = mycolor_element;
h1 {
  color: orange
}
<h1 id='my_id'>Hello</h1>
<div id='my_element'>
  <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">

  <path d="M10 10"/>

  <!-- Points -->
  <circle cx="10" cy="10" r="10" fill="red"/>

</svg>
</div>

CodePudding user response:

querySelectorAll returns a static NodeList (see mdn)

one way to access the elements is by using Array.from(document.querySelectorAll("selector"))

mycolor_element = document.querySelectorAll("#my_id_h1")[0];

let my_value = window.getComputedStyle(mycolor_element).color;

Array.from(document.querySelectorAll("#my_element")).forEach(el => el.style.color = my_value)

also note, that id's values must not contain whitespaces!

CodePudding user response:

 document.querySelectorAll

This method is not used to select one element only. Use the

document.querySelector

method instead.

  • Related