code everywhere

importing RSS feeds onto your page using fetch()

posted on November 8, 2019, 12:00 am in

We're going to use the New York Times open RSS feeds (available here: www.nytimes.com/rss) to show how we can pull in RSS/XML data into any webpage.

The 3 main points are using fetch() to get the XML, parsing the fetched data using DOMParser() and injecting your content into a template for displaying on any page.

Here is the code below;

fetch('https://rss.nytimes.com/services/xml/rss/nyt/Technology.xml')
  .
then(function(resp) { return resp.text() })
  .
then(function(xml) { return (new window.DOMParser()).parseFromString(xml"text/xml") })
  .
then(function(resp) {

    const 
items resp.getElementsByTagName('item')
    
let buffer "";
    for (var 
0items.length && 5x++) {

      const 
title items[x].getElementsByTagName('title')[0].textContent
      
const date items[x].getElementsByTagName('pubDate')[0].textContent
      
const content items[x].getElementsByTagName('description')[0].textContent
      
      buffer 
+= `
      <div style="
        margin:10px; padding: 5px; background: #ebebebff; border-left: 4px solid #a2a2a2ff;
      ">
        <div>
${title}</div>
        <div style="font-size:small">
${date}</div>
        <div style="font-size:small">
${content}</div>
      </div>
`
    }
    
document.getElementById('rss-feed').innerHTML buffer
  
})

The final result, a list of articles inserted into our page. These are a live feed from rss.nytimes.com.

Demo

< back
find something helpful? send us some coin BTC 19u6CWTxH4cH9V2yTfAemA7gmmh7rANgiv

(ad) Need Hosting? Try Linode, VPS Starting from $5

privacy policy