Search code examples
javascriptclosestselectors-apigetattribute

Get value of specific data-attribute of closest element containg it gives TypeError


In my library I want to write a little function for closest() and especially get the value of a specific data-attribut of closest element because in my Application I need to use this very very often. :D

But I only get told by the console:

TypeError: x.getAttribute is not a function

var $ = function(s) {
  var x;
  var obj = {
    myLib(s) {
      return x || querySelectorAll(s);
    },
    myFunction(s) {
      if (s.startsWith('data-')) { // in this block is sth. wrong
        x = [x[0].closest('*["' + s + '"]')];
        return x.getAttribute(s);
      } else {
        x = [x[0].closest(s)];
        return this;
      }
    }
  };
  x = obj.myLib(s);
  return obj;
};

////////// usage examples

// get the value of attribute "data-wrestler"
var dv = $('.kilo').myFunction('data-wrestler');
console.log(dv);

// select the closest element by selector
var ce = $('.kilo').myFunction('.uniform');
console.log(ce);

// would select the closest element with specific data-attribut by selector
var da = $('.kilo').myFunction('*["data-wrestler"]');
console.log(da);
<div id="foxtrott">
  foxtrott
  <div class="uniform" data-wrestler="hulkster">
    uniform
    <div class="charlie">
      charlie
      <div class="kilo">
        kilo
      </div>
    </div>
  </div>
</div>


Solution

    1. Quotes [data-wrestler] - remove them x = [x[0].closest('[' + s + ']')];

    2. You use document.querySelectorAll - it returns a collection so you need to use [0]

      return x[0].getAttribute(s);

    or change to document.querySelector