1

I'm attempting to better understand javascript so I decided to write a basic JQuery like library using vanilla javascript.The problem I'm having is that I'm trying to get an html element's attribute or set an html element's attribute depending on the way the function is called but I continue to get undefined. I thought that maybe since It was reading as undefined I would just need to return the function but then I got not null. I'm a little stranded look for a map.Please Help

So I've used the querySelector as well as the getAttribute function but it reads as undefined. I assume since its undefined that its in memory just undefined. Can someone help a lost brain.

function legion(selector) {
  const self = {
    attr: (attribute, value) => {
      if (value == null) {
        console.log("get")
        self.element.querySelector(attribute)
      } else if (value) {
        console.log("set")
        self.element.setAttribute(attribute, value)
      }
    },
  }
  
  return self;
};

console.log(legion("h1").attr(".class"))
<h1 class="class">h1</h1>
<h2 id="h2">h2</h2>
<h3 data="true">h3</h3>

I expected the console to log class

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
TGardner
  • 27
  • 6

1 Answers1

1

Here's what you probably tried to achieve

function legion(selector) {
  const self = {
    element: document.querySelector(selector),
    attr: (attribute, value) => {
      if (value) {
        self.element.setAttribute(attribute, value)
        return self
      }
      return self.element.getAttribute(attribute)
    },
  }
  return self;
};

legion("h1").attr("class", "red")
console.log(legion("h1").attr("class"))
.red {
  color: red;
}
<h1 class="class">h1</h1>
<h2 id="h2">h2</h2>
<h3 data="true">h3</h3>
Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69