Skip to content

Commit

Permalink
change the API so it takes an array
Browse files Browse the repository at this point in the history
  • Loading branch information
nichoth committed Jul 18, 2024
1 parent 9cb7352 commit 3c35109
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 12 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,17 @@ import { attributesToString } from '@substrate-system/util'

### `attributesToString`

Take an `HTMLElement`, and transform its attributes into a string format. This is sometimes useful for creating [web components](https://developer.mozilla.org/en-US/docs/Web/API/Web_components).
Take an array of attributes, and transform them into a string format. This can be useful for creating [web components](https://developer.mozilla.org/en-US/docs/Web/API/Web_components).

```ts
function attributesToString (el:HTMLElement):string {
function attributesToString (attrs:Attr[]):string {
```
#### example
```ts
import { attributesToString } from '@substrate-system/util'
const el = document.getElementById('example')
const str = attributesToString(el!)
const str = attributesToString(Array.from(el!.attributes))
console.log(str)
// => 'type="text" id="example" required'
```
Expand Down
4 changes: 2 additions & 2 deletions example/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import { attributesToString } from '../src/index.js'
const debug = Debug()

const el = document.getElementById('example')
const str = attributesToString(el!)
const str = attributesToString(Array.from(el!.attributes))

debug('attributes as string', str)
debug('attributes as string', `'${str}'`)
12 changes: 5 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
/**
* Get attributes from an HTMLElement, and return them as a string
* like `key=val`.
* @param {HTMLElement} el The element to get attributes from
* @returns {string} The attributes as a string of `key=val`
* @param {Attr[]} attrs An array of the attributes
* @returns {string} The attributes as a string like `key=val`
*/
export function attributesToString (el:HTMLElement):string {
return Array.from(el.attributes)
.filter(attr => !attr.name.includes('display-name'))
.map(attr => attr.name + (attr.value === '' ? '' : '=' +
`"${attr.value}"`))
export function attributesToString (attrs:Attr[]):string {
return attrs.map(attr => attr.name + (attr.value === '' ? '' : '=' +
`"${attr.value}"`))
.join(' ')
}

Expand Down

0 comments on commit 3c35109

Please sign in to comment.