DEV Community

ahoNerd
ahoNerd

Posted on • Edited on • Originally published at ahonerd.com

2 1

Add Multiple Attribute to an Element using javaScript

Untuk menambah beberapa attribute pada sebuah HTML element dengan menggunakan javaScript dapat menggunakan beberapa cara yang akan kita bahas berikut ini.

Function Expression

Code berikut ditulis dalam format TypeScript:

Methode #1

const setMultipleAttr = (elm: any, attributes: any) => {
  for (const key in attributes)
    elm.setAttribute(key, attributes[key])
}
Enter fullscreen mode Exit fullscreen mode

Methode #2

const setMultipleAttr = (elm: any, attributes: any) => {
  Object.keys(attributes).forEach((attr) => {
    elm.setAttribute(attr, attributes[attr])
  })
}
Enter fullscreen mode Exit fullscreen mode

CodePen

Reference

eveloper.mozilla.org/en-US/docs/Web/API/Element/setAttribute

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE