JS Feed Parsing (with CORS)

by dledle2

HTML

<div id="npr-feed">Loading...</div>

CSS

body {
    padding: 1em;
}

h1 {
    font-size: 2em;
    margin-bottom: 1em;
}

ul {
    margin-left: 1em;
    list-style-type: disc;
}

JavaScript

const RSS_URL = `https://npr.org`;

fetch(RSS_URL)
  .then(response => response.text())
  .then(str => new window.DOMParser().parseFromString(str, "text/xml"))
  .then(data => {
    const items = data.querySelectorAll("item");
    const container = document.getElementById("npr-feed");
    container.innerHTML = ""; // Clear loader
    
    items.forEach(el => {
      container.insertAdjacentHTML("beforeend", `
        <div class="news-item">
          <a href="${el.querySelector("link").innerHTML}">
            ${el.querySelector("title").innerHTML}
          </a>
        </div>
      `);
    });
  });