querySelector returns 'undefined'

<div id="~" class="dm-post-0 well clearfix post listview"
    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?

>Solution :

When you iterate over these elements returned 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="~" class="dm-post-0 well clearfix post listview" data-identifier="~" data-relative="https://~" data-feed="~">
<div id="~" class="dm-post-0 well clearfix post listview" data-identifier="~" data-relative="https://~1" data-feed="~">

Leave a Reply