Home > Software design >  Javascript trying to get value of an element not working
Javascript trying to get value of an element not working

Time:03-18

My code:

function $(selector){
    var self = {
        el:document.querySelector(selector),
        html:()=> self.el.innerHTML,
        on:(event, callback)=>{
            document.addEventListener(event, callback)
        },
        hide:()=> {
            self.el.style.display = 'none'
        },
        attr:(attr, value)=>{
            if(value == null){
                self.el.getAttribute(attr)
            }else{
            self.el.setAttribute(attr, value);
            }
        },
        setHTML:(code)=>{
            self.el.innerHTML = "";
            self.el.innerHTML = code;
        },
        createChld:(childElement, id, clss, innerHTML)=>{
            var el = document.createElement(childElement);
            el.setAttribute('id', id);
            el.setAttribute('class', clss);
            el.innerHTML = innerHTML;
            self.el.appendChild(el);
        },
        addClass:(clss)=>{
            self.el.classList.add(clss)
        },
        addId:(id)=>{
            self.el.id = id;
        },
        value:()=>{
            self.el.value;
        }
    }
    return self
}


When I try to use something like $('input').value() it doesn't work it just results to undefinded, I don't know why but I think it has something to do with self.el.value. Thanks.

CodePudding user response:

Arrow functions need a return statement if they are wrapped with {}. Use:

        value: ()=>{
            return self.el.value;
        }

Alternatively, you could not use curly brackets.

        value: ()=>self.el.value;

CodePudding user response:

You must add the return:

self.value=()=>{
     return self.el.value;
}
  • Related