1252748
1252748

Reputation: 15372

How can I attach a method to an object to change CSS

I wanted to make a method so that I could dynamically change CSS of an element without the longhanded methods document.getElementsByTagName("div")[0].style.borderColor = "red" and implement something like happens in the jQuery library. However, when I try to attach a css method to an element like this

var __shorthandCss = function(sel){

  var el = document.querySelectorAll(sel)[0];
  el.css = function(attrs){

       for (var attr in attrs){
         el.style[attr] = attrs[attr];
       }

  };

};

I get the error:

Uncaught TypeError: Cannot read property 'css' of undefined

What have I done wrong here? Have I gone about this in completely the wrong manner?

var __shorthandCss = function(sel) {

  var el = document.querySelectorAll(sel)[0];
  console.log(el);
  el.css = function(attrs) {

    for (var attr in attrs) {
      console.log(attr, attrs)
      el.style[attr] = attrs[attr];
    }

  };

};
var trig = function() {
  __shorthandCss("#a").css({
    "borderColor": "red"
  });
  console.log(a);
};
document.getElementById("b").addEventListener("click", trig);
div {
  border: 1px solid black;
  padding: 5px;
  width: 150px;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>

<body>
  <button type="button" id="b">change border</button>
  <div id="a">test div</div>
</body>

</html>

Upvotes: 0

Views: 51

Answers (1)

A.B
A.B

Reputation: 20445

you are not returning el from the function

when you call __shorthandCss() nothing is returned on which css() function is present as an property so you need to return el on which you have assigned css()

var __shorthandCss = function(sel){

  var el = document.querySelectorAll(sel)[0];
  console.log(el);
  el.css = function(attrs){

       for (var attr in attrs){
         console.log(attr, attrs)
         el.style[attr] = attrs[attr];
       }

  };
  return el;
};

Recomendation

You can use document.querySelector(sel) instead of document.querySelectorAll(sel)[0] as it does same thing

Working Demo:

var __shorthandCss = function(sel){
  
  var el = document.querySelector(sel);
  console.log(el);
  el.css = function(attrs){
    
       for (var attr in attrs){
         console.log(attr, attrs)
         el.style[attr] = attrs[attr];
       }
    
  };
  return el;
};
var trig = function(){
   __shorthandCss("#a").css({"borderColor": "red"});
   console.log(a);
};  
document.getElementById("b").addEventListener("click", trig);

  
  
div{
  border: 1px solid black;
  padding: 5px;
  width: 150px;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <button type="button" id="b">change border</button>
  <div id="a">test div</div>
</body>
</html>

Upvotes: 3

Related Questions