Get all Attributes from a HTML element with Javascript/jQuery

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

    Every answer here is missing the simplest solution using the getAttributeNames element method!

    It retrieves the names of all the element's current attributes as a regular Array, that you can then reduce to a nice object of keys/values.

    const getAllAttributes = el => el
      .getAttributeNames()
      .reduce((obj, name) => ({
        ...obj,
        [name]: el.getAttribute(name)
      }), {})
    
    console.log(getAllAttributes(document.querySelector('div')))

提交回复
热议问题