Get all Attributes from a HTML element with Javascript/jQuery

后端 未结 17 1787
时光说笑
时光说笑 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:53

    Attributes to Object conversion

    *Requires: lodash

    function getAttributes(element, parseJson=false){
        let results = {}
        for (let i = 0, n = element.attributes.length; i < n; i++){
            let key = element.attributes[i].nodeName.replace('-', '.')
            let value = element.attributes[i].nodeValue
            if(parseJson){
                try{
                    if(_.isString(value))
                    value = JSON.parse(value)
                } catch(e) {}
            }
            _.set(results, key, value)
        }
        return results
    }
    

    This will convert all html attributes to a nested object

    Example HTML:

    Result: {custom:{nested:{path1:"value1",path2:"value2"}}}

    If parseJson is set to true json values will be converted to objects

提交回复
热议问题