0

i want to assigned css inline style from one element to other element. example.

i want to copy style form btn1 and assign to btn 2

<button id="btn1" style="font-size: 10px;background-color: #4CAF50;  padding: 10px 24px;">Button 1</button>

  <button id="btn2" style="font-size: 10px;background-color: rgb(93, 16, 3); background:beige ; padding: 10px 24px;">Button 2</button>
  • Possible duplicate of [Set / Copy javascript computed style from one element to another](https://stackoverflow.com/questions/19784064/set-copy-javascript-computed-style-from-one-element-to-another) – Roy Bogado Sep 03 '19 at 09:13

3 Answers3

0

Get the style attribute from the first element and use that value to set the style attribute on the other one.

let styles = document.querySelector('#btn1').getAttribute('style')

document.querySelector('#btn2').setAttribute('style', styles)
<button id="btn1" style="font-size: 10px;background-color: #4CAF50;  padding: 10px 24px;">Button 1</button>
<button id="btn2">Button 2</button>
James Coyle
  • 9,922
  • 1
  • 40
  • 48
0

Get style attribute from one element using getAttribute() and apply to other element using setAttribute()

document.querySelector('#btn2').setAttribute('style',document.querySelector('#btn1').getAttribute('style'))
<button id="btn1" style="font-size: 10px;background-color: #4CAF50;  padding: 10px 24px;">Button 1</button>

  <button id="btn2" style="font-size: 10px;background-color: rgb(93, 16, 3); background:beige ; padding: 10px 24px;">Button 2</button>
James Coyle
  • 9,922
  • 1
  • 40
  • 48
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

You can use the getAttribute and setAttribute methods of the HTML elements, like:

const btn1 = document.getElementById("btn1");
const btn2 = document.getElementById("btn2");

btn2.addEventListener("click", copyStyles);

function copyStyles(){
  const style = btn1.getAttribute("style");
  btn2.setAttribute("style", style);
}
<button
  id="btn1"
  style="font-size: 10px; background-color: #4CAF50;  padding: 10px 24px;"
>Button 1</button>

<button
  id="btn2"
  style="font-size: 10px; background-color: rgb(93, 16, 3); background:beige; padding: 10px 24px;"
>Button 2</button>
Cat
  • 4,141
  • 2
  • 10
  • 18