惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
博客园 - Franky
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
腾讯CDC
D
Docker
The Cloudflare Blog
量子位
爱范儿
爱范儿
L
LangChain Blog
博客园 - 三生石上(FineUI控件)
博客园 - 司徒正美
aimingoo的专栏
aimingoo的专栏
Blog — PlanetScale
Blog — PlanetScale
Jina AI
Jina AI
Apple Machine Learning Research
Apple Machine Learning Research
Hugging Face - Blog
Hugging Face - Blog
博客园 - 聂微东
Vercel News
Vercel News
MyScale Blog
MyScale Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Build a Simple RSS Feed Widget in Vanilla JavaScript
Debate Me · 2026-06-18 · via DEV Community

RSS has been around for over two decades and it is still one of the most useful formats on the web. Every major blog, news site, and podcast publishes one. But most developers reach for heavy frameworks or third-party widgets when they want to display feed content on a page. The truth is that RSS is just XML and the browser already knows how to parse XML natively without any libraries or dependencies at all.

In this tutorial we are going to build a clean, card-based RSS widget using nothing but vanilla JavaScript and a handful of CSS. The end result pulls live posts from any RSS feed and renders them as a responsive grid of cards with titles, category badges, descriptions, and publication dates.

We will use how-to-do.net/feed.xml as our working example throughout because it has a clean standard RSS 2.0 structure that makes it easy to follow along.

What the feed looks like

Before we write any code, let's look at what we are working with. An RSS feed is just an XML document with a predictable structure. Here is a simplified version of what comes back:

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <title>How To Do</title>
    <link>https://how-to-do.net</link>
    <description>Clear, friendly step-by-step guides for real life.</description>
    <language>en-us</language>
    <lastBuildDate>Sun, 14 Jun 2026 12:00:00 GMT</lastBuildDate>
    <item>
      <title>How to Cook Ribs in the Oven</title>
      <link>https://how-to-do.net/guides/how-to-cook-ribs-in-the-oven</link>
      <description>Learn how to cook pork ribs in the oven with a simple foil-wrap method...</description>
      <category>Cooking &amp; Food</category>
      <pubDate>Sun, 14 Jun 2026 12:00:00 GMT</pubDate>
    </item>
    <!-- more items -->
  </channel>
</rss>

The <channel> element holds metadata about the feed itself, and each <item> represents a single post. Every item in this feed has five fields we care about: title, link, description, category, and pubDate. That is everything we need to build a nice-looking card.

Dealing with CORS first

If you try to fetch an RSS feed from the browser and the feed's server does not include an Access-Control-Allow-Origin header, the browser will block the response before your JavaScript can even see it. This is the most common stumbling block when building anything that fetches external content client-side.

The good news is that some feeds already have CORS enabled. The feed we are using in this tutorial (how-to-do.net/feed.xml) sets Access-Control-Allow-Origin: *, which means we can fetch it directly without any workarounds:

const FEED_URL = 'https://how-to-do.net/feed.xml';

async function fetchFeed(url) {
  const response = await fetch(url);
  const text = await response.text();

  if (!text || !text.includes('<rss')) {
    throw new Error('Invalid RSS response');
  }

  return text;
}

If you want to use this widget with a feed that does not have CORS enabled, you will need to route the request through a proxy. You can use a free service like allorigins.win for prototyping by changing the fetch URL to https://api.allorigins.win/raw?url= followed by your encoded feed URL. For anything production-facing, a small Cloudflare Worker is a more reliable option and takes about two minutes to deploy

// Cloudflare Worker (wrangler deploy)
export default {
  async fetch(request) {
    const url = new URL(request.url);
    const feedUrl = url.searchParams.get('url');

    if (!feedUrl) {
      return new Response('Missing url parameter', { status: 400 });
    }

    const feed = await fetch(feedUrl);
    const body = await feed.text();

    return new Response(body, {
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/xml',
      },
    });
  },
};

Parsing the XML into usable data

The browser has a built-in DOMParser that turns raw XML into a document you can query with the same methods you use for HTML. No libraries needed, no npm install, just native browser APIs

function parseFeed(xmlText) {
  const parser = new DOMParser();
  const xml = parser.parseFromString(xmlText, 'application/xml');

  const channel = xml.querySelector('channel');
  const feedTitle = channel.querySelector('title').textContent;
  const feedLink = channel.querySelector('link').textContent;
  const feedDescription = channel.querySelector('description').textContent;

  const items = Array.from(xml.querySelectorAll('item')).map(item => ({
    title: item.querySelector('title').textContent,
    link: item.querySelector('link').textContent,
    description: item.querySelector('description').textContent,
    category: item.querySelector('category')?.textContent || 'General',
    pubDate: new Date(item.querySelector('pubDate').textContent)
  }));

  return { feedTitle, feedLink, feedDescription, items };
}

What we get back is a JavaScript object containing the feed metadata and an array of post objects. Each post has a title, link, description, category (like "Cooking & Food" or "Tech & Digital"), and a proper Date object for the publication date.

The feed from how-to-do.net returns 20 items covering 11 categories including things like "Health & Wellness", "Auto & Vehicle", "Finance & Money", and "Sports & Recreation". This variety is actually great for testing because it lets us build category filtering later.

Rendering the cards

Now that we have structured data we can build the UI. Each card will show the category as a colored badge at the top, followed by the title, publication date, a short description, and a link to the full guide

function renderFeed(feedData, container) {
  container.innerHTML = '';

  const header = document.createElement('div');
  header.className = 'feed-header';
  header.innerHTML = `
    <h2><a href="${feedData.feedLink}" target="_blank">${feedData.feedTitle}</a></h2>
    <p>${feedData.feedDescription}</p>
  `;
  container.appendChild(header);

  const grid = document.createElement('div');
  grid.className = 'feed-grid';

  feedData.items.forEach(item => {
    const card = document.createElement('article');
    card.className = 'feed-card';

    const formattedDate = item.pubDate.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });

    card.innerHTML = `
      <span class="feed-card-category">${item.category}</span>
      <h3 class="feed-card-title">
        <a href="${item.link}" target="_blank">${item.title}</a>
      </h3>
      <time class="feed-card-date">${formattedDate}</time>
      <p class="feed-card-description">${item.description}</p>
      <a href="${item.link}" class="feed-card-link" target="_blank">Read guide →</a>
    `;

    grid.appendChild(card);
  });

  container.appendChild(grid);
}

Styling the grid

The CSS is intentionally minimal. A responsive grid layout that starts at one column on mobile and expands to three columns on larger screens, with clean card styling and category badges that add a bit of color

.feed-header {
  margin-bottom: 24px;
}

.feed-header h2 a {
  color: inherit;
  text-decoration: none;
}

.feed-header p {
  color: #666;
  margin-top: 4px;
}

.feed-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.feed-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  transition: box-shadow 0.2s;
}

.feed-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.feed-card-category {
  display: inline-block;
  background: #e8f4f8;
  color: #1a6b8a;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  margin-bottom: 12px;
  align-self: flex-start;
}

.feed-card-title {
  margin: 0 0 8px;
  font-size: 18px;
  line-height: 1.3;
}

.feed-card-title a {
  color: inherit;
  text-decoration: none;
}

.feed-card-title a:hover {
  color: #1a6b8a;
}

.feed-card-date {
  font-size: 13px;
  color: #999;
  margin-bottom: 12px;
}

.feed-card-description {
  font-size: 14px;
  color: #555;
  line-height: 1.5;
  flex-grow: 1;
}

.feed-card-link {
  font-size: 14px;
  color: #1a6b8a;
  text-decoration: none;
  font-weight: 600;
  margin-top: 12px;
}

.feed-card-link:hover {
  text-decoration: underline;
}

Putting it all together

Here is the complete wiring that fetches the feed, parses it and renders the cards into a container element on the page

async function loadRSSWidget(feedUrl, containerSelector) {
  const container = document.querySelector(containerSelector);

  try {
    container.innerHTML = '<p>Loading feed...</p>';
    const xmlText = await fetchFeed(feedUrl);
    const feedData = parseFeed(xmlText);
    renderFeed(feedData, container);
  } catch (error) {
    container.innerHTML = '<p>Could not load feed. Please try again later.</p>';
    console.error('RSS Widget Error:', error);
  }
}

// Initialize with the How To Do feed
loadRSSWidget('https://how-to-do.net/feed.xml', '#rss-widget');

And in your HTML you just need a container div

<div id="rss-widget"></div>

That is the entire widget. Just a single JavaScript file and some CSS that you can drop into any project.

Adding category filtering

Since the feed has 11 different categories, it would be nice to let users filter by the topics they care about. Here is a quick enhancement that adds clickable filter buttons above the grid

function renderFilters(feedData, container, grid) {
  const categories = [...new Set(feedData.items.map(item => item.category))].sort();

  const filterBar = document.createElement('div');
  filterBar.className = 'feed-filters';
  filterBar.innerHTML = `<button class="feed-filter active" data-category="all">All</button>` +
    categories.map(cat =>
      `<button class="feed-filter" data-category="${cat}">${cat}</button>`
    ).join('');

  filterBar.addEventListener('click', (e) => {
    if (!e.target.matches('.feed-filter')) return;

    filterBar.querySelectorAll('.feed-filter').forEach(btn => btn.classList.remove('active'));
    e.target.classList.add('active');

    const selected = e.target.dataset.category;
    grid.querySelectorAll('.feed-card').forEach((card, index) => {
      const item = feedData.items[index];
      card.style.display = (selected === 'all' || item.category === selected)
        ? 'flex'
        : 'none';
    });
  });

  container.insertBefore(filterBar, grid);
}

With some extra CSS for the filter buttons

.feed-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 20px;
}

.feed-filter {
  background: #f0f0f0;
  border: none;
  padding: 6px 14px;
  border-radius: 16px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s;
}

.feed-filter:hover {
  background: #e0e0e0;
}

.feed-filter.active {
  background: #1a6b8a;
  color: white;
}

Now users can click "Cooking & Food" to see just the cooking guides, or "Tech & Digital" for the tech ones, or "All" to reset.

Making it reusable

The nice thing about this approach is that it works with any standard RSS feed. You can swap out the URL and the widget rebuilds itself automatically

// A how-to blog
loadRSSWidget('https://how-to-do.net/feed.xml', '#widget-1');

// A tech news feed
loadRSSWidget('https://feeds.arstechnica.com/arstechnica/index', '#widget-2');

// A podcast feed
loadRSSWidget('https://some-podcast.com/feed.xml', '#widget-3');

Each instance handles its own data, its own categories, and its own error state. You could put five different feeds on one page and they would all work independently.

Where to go from here

If you want to extend this further, here are some ideas that build naturally on top of what we have

Auto-refresh by wrapping the load function in a setInterval that re-fetches every 15 or 30 minutes so the widget stays current without a page reload

Search by adding a text input that filters cards based on whether the title or description contains the search term, which is just a small extension of the category filter logic we already wrote

Caching by storing the parsed feed data in sessionStorage with a timestamp, and only re-fetching when the cache is older than a threshold you define

Dark mode by swapping the hardcoded colors for CSS custom properties and toggling a class on the container

The full source code is available as a single HTML file you can drop into any project. The example feed comes from How To Do, which publishes practical step-by-step guides covering everything from cooking and home maintenance to personal finance and technology.


Happy building, and if you end up using this in a project I would love to see what you make with it.