Skip to content

Instantly share code, notes, and snippets.

@andremalveira
Last active July 25, 2022 02:49
Show Gist options
  • Save andremalveira/ed6ec932b60d9484ca1a8c0d32e72f6c to your computer and use it in GitHub Desktop.
Save andremalveira/ed6ec932b60d9484ca1a8c0d32e72f6c to your computer and use it in GitHub Desktop.
⭐ document.getElementByAttribute() - JavaScript Vanilla

Creating getElementByAttribute function.

📌 getElementByAttribute Return only one element

document.getElementByAttribute = HTMLElement.prototype.getElementByAttribute = function(attribute) {
  let e = this.querySelector(`[${attribute}]`) ?? this.querySelector(`[data-${attribute}]`)
  let value = e.getAttribute(`${attribute}`) ?? e.getAttribute(`data-${attribute}`)
  
  let rgx = /^[0-9.]+$/
  if(rgx.test(value)) value = Number(value)

  e.value = value
  return e
}

📌 getElementsByAttribute Return an array with all elements that have the attribute

document.getElementsByAttribute = HTMLElement.prototype.getElementsByAttribute = function(attribute) {
  let e = this.querySelectorAll(`[${attribute}]`) ?? this.querySelectorAll(`[data-${attribute}]`)
  return Array.prototype.map.call(e, (e => {
    let value = e.getAttribute(`${attribute}`) ?? e.getAttribute(`data-${attribute}`)
  
    let rgx = /^[0-9.]+$/
    if(rgx.test(value)) value = Number(value)
  
    e.value = value
    return e 
  }))
}

How to use:

document.getElementByAttribute('data-attribute-name')
// or 
let element = document.body
element.getElementByAttribute('data-attribute-name')

Example:

<body>
  <div id="element">
    <div data-attribute-name="attribute-value-1"></div>
    <div data-attribute-name="attribute-value-2"></div>
    <div data-attribute-name="attribute-value-3"></div>
  </div>
</body
document.getElementByAttribute('data-attribute-name') // or 'attribute-name'
// Result: <div data-attribute-name="attribute-value"></div>

// or

document.getElementsByAttribute('data-attribute-name') // or 'attribute-name'
// Result: 
//  [
//    0: div
//    1: div
//    2: div
//  ]

Getting attribute value

document.getElementByAttribute('data-attribute-name').value
// Result: attribute-value

// or

let attrElement = document.getElementsByAttribute('data-attribute-name')
attrElement.forEach(e => {
  console.log(e.value) 
})
// Result
// attribute-value1
// attribute-value2
// attribute-value3


by André Malveira

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment