Get all Attributes from a HTML element with Javascript/jQuery

后端 未结 17 2088
时光说笑
时光说笑 2020-11-22 05:07

I want to put all attributes in a Html element into an array: like i have a jQuery Object, whichs html looks like this:



        
17条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 05:51

    Try something like this

        

    and then get all attributes

        const foo = document.getElementById('foo');
        // or if you have a jQuery object
        // const foo = $('#foo')[0];
    
        function getAttributes(el) {
            const attrObj = {};
            if(!el.hasAttributes()) return attrObj;
            for (const attr of el.attributes)
                attrObj[attr.name] = attr.value;
            return attrObj
        }
    
        // {"id":"foo","[href]":"url","class":"","(click)":"alert('hello')","data-hello":"world"}
        console.log(getAttributes(foo));
    

    for array of attributes use

        // ["id","[href]","class","(click)","data-hello"]
        Object.keys(getAttributes(foo))
    

提交回复
热议问题