Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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="~">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading