0

I was trying to pass the CSS of a element to another element, I wrote a function (demo included):

extendcss = (el1, el2) => {
     if(typeof(el1) == 'object' && typeof(el2) == 'object'){
     Array.prototype.slice.call(el1.attributes).forEach(function (item) {
       el2.setAttribute(item.name, item.value);
     });
   }
   else{
     Array.prototype.slice.call(document.querySelector(el1).attributes).forEach(function (item) {
       document.querySelector(el2).setAttribute(item.name, item.value);
     });
   }
   }
 $('button').click(()=>{
 extendcss('#parent', '#child');
 });
#parent{
color: white;
background: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="parent">Parent</h1>
<h1 id="child">Child</h1>
<button>DO</button>

The problem is that, when the method is called, all the attributes of the first element, like id, class, style, and other things get included and added to second element. I haven't figured out how to pass the style only to the second element.

Please help me in passing only style of the element from the element.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Pranav
  • 674
  • 1
  • 6
  • 23
  • The `style` object only contains style information that's directly on the elements; that is, the contents of the `style` attribute itself. CSS rules have no effect on that; you have to use `.getComputedStyle()` – Pointy Oct 16 '19 at 13:40
  • but the `.getComputedStyle()` also returns all the unnecessary and undefined things. I don't want that – Pranav Oct 16 '19 at 13:41
  • The most usable/easy way to do this is create a class and share with any elements that you want. – Vinicius Dutra Oct 16 '19 at 13:43
  • No, @ViniciusDutra, this is not what I wanted – Pranav Oct 16 '19 at 13:45
  • 1
    If you don't want to share `getComputedStyle` nor share a class, then you're either needlessly complicating the *solution* or perhaps *the requirement*. This seems a bit like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - can you say what are you actually trying to solve? – VLAZ Oct 16 '19 at 13:48
  • @ObnoxiousNerd, if you want really to do this, i suggest you to do what aready said before, use .getComputedStyle(), but with a virtual element that implement the rules that you want, for this, you can use a class – Vinicius Dutra Oct 16 '19 at 13:49
  • Could you just comment a way to do that, @ViniciusDutra – Pranav Oct 16 '19 at 13:50
  • look here https://stackoverflow.com/questions/324486/how-do-you-read-css-rule-values-with-javascript at the first answer the getStyle function – user254694 Oct 16 '19 at 13:53
  • I'd probably go for second answer, that worked. Thanks, user – Pranav Oct 16 '19 at 13:58

0 Answers0