1

I always get [Object object] or are creating a conflict no matter how hard I try. (I tried a couple of other variants.) ;(

var $ = function(selector){

  var x; 
  var obj = {
  
    myLib(selector){
      return x || document.querySelectorAll(selector);
    },
    
    cl(selector){
      x = [x[0].closest(selector)];
      return this;
    },    
      
    attr(s,v){
      s&&v ? x.forEach(y=>{y.setAttribute(s,v);})
           : x = [x[0].getAttribute(s)]; x.value; // what is wrong here ?
      return this;
    },
      
  };
        
  x = obj.myLib(selector);
  return obj;
  
};

var wtf = $('.kilo').cl('.uniform').attr('data-wrestler');

console.log('WTF: '+wtf);
console.log('WTF: '+JSON.stringify(wtf));
<div id="foxtrott">
  foxtrott
  <div class="uniform" data-wrestler="hulkster">
    uniform
    <div class="charlie">
      charlie
      <div class="kilo">
        kilo
      </div>
    </div>
  </div>
</div>

If you also have useful links to read about this topic this would be very nice.

Thanks in advance, guys !!!

4
  • How are you using this? It isn't clear. Commented Oct 30, 2019 at 10:50
  • 1
    yes, sorry! i update my question in a minute Commented Oct 30, 2019 at 10:53
  • Why do you have x.value; ? It is a separate statement, so you'd better write it on a separate line. Commented Oct 30, 2019 at 10:53
  • because x = [x[0].getAttribute(s)].value; didn't work Commented Oct 30, 2019 at 11:00

1 Answer 1

2

You should return x instead of this in the attr method

var $ = function(selector){

  var x; 
  var obj = {
  
    myLib(selector){
      return x || document.querySelectorAll(selector);
    },
    
    cl(selector){
      x = [x[0].closest(selector)];
      return this;
    },    
      
    attr(s,v){
      s&&v ? x.forEach(y=>{y.setAttribute(s,v);})
           : x = [x[0].getAttribute(s)]; 
      return x;
    },
      
  };
        
  x = obj.myLib(selector);
  return obj;
  
};

var wtf = $('.kilo').cl('.uniform').attr('data-wrestler');

console.log('WTF: '+wtf);
console.log('WTF: '+JSON.stringify(wtf));
<div id="foxtrott">
  foxtrott
  <div class="uniform" data-wrestler="hulkster">
    uniform
    <div class="charlie">
      charlie
      <div class="kilo">
        kilo
      </div>
    </div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Then you'd loose the chaining at attr setting. Make it return the string only when it is getting it, returning this otherwise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.