<div id="~"
data-identifier="~" data-relative="https://~"
data-feed="~">
let convertEntries = () => {
"use strict";
let target = [...document.getElementsByClassName("listview")];
target.forEach((element) => {
result.push({
url: element.querySelector("#listview").dataset.relative,
});
});
return result;
};
How can I capture the contents of the data-relative
attribute instead of returning undefined
?
CodePudding user response:
When you iterate over these elements in the HTML collection returned by getElementsByClassName
you only need to get the dataset value from the current iterated element.
element.dataset.relative
Since you're doing an array-like collection => array conversion you may as well use map
to build the array of objects to save declaring a separate result
array.
And querySelectorAll
is shorter to type.
function convertEntries() {
const list = [...document.querySelectorAll('.listview')];
return list.map(element => {
return { url: element.dataset.relative };
});
}
console.log(convertEntries());
<div id="~" data-identifier="~" data-relative="https://~" data-feed="~">
<div id="~" data-identifier="~" data-relative="https://~1" data-feed="~">