I'm using jQuery to parse and output three RSS feeds into three different container divs. The first two feeds work fine, but I can't get the links to work in the third feed, the href isn't found at all. See fiddle http://jsfiddle.net/a68myvm2/1/
I'm thinking that it has to do with that the third feed contains multiple link tags per item. I've tried searching the web for a solution without success.
HTML
<div id="content_1"></div>
<div id="content_2"></div>
<div id="content_3"></div>
JS
$(function () {
function GetFeeds(){
var urls = ['http://www.gosugamers.net/counterstrike/news/rss', 'http://www.hltv.org/news.rss.php', 'http://feeds.thescoreesports.com/csgo.rss'];
urls.forEach(function(Query){
$.ajax({
type: "GET",
url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q='+encodeURIComponent(Query),
dataType: 'json',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function(xml) {
var Content=parseInt(urls.indexOf(Query))+1;
$("#content_"+Content).html('');
$.each(xml.responseData.feed.entries, function(idx, value){
$("#content_"+Content).append('<a class="news-item" href="' + value.link + '" title="' + value.title +'" target="_blank"><p>' + value.publishedDate + '</p><h3>' + value.title + '</h3></a><hr>');
});
}
});
});
}
//Call GetFeeds every 5 seconds.
setInterval(GetFeeds,5000);
//Page is ready, get feeds.
GetFeeds();
});
Part of problematic feed (http://feeds.thescoreesports.com/csgo.rss)
<item>
<guid isPermaLink="false">4117</guid>
<title>ScrunK joins Team Coast as Coach</title>
<link>http://www.thescoreesports.com/news/4117</link>
<pubDate>Wed, 30 Sep 2015 18:02:45 +0000</pubDate>
<dc:creator/>
<media:content url="https://dqrt72khb0whk.cloudfront.net/uploads/image/file/2729/w1080xh810_coast.jpg?ts=1432916713">
<media:credit>Team Coast</media:credit>
</media:content>
<content:encoded>
<![CDATA[<p>Team Coast have brought in German CS:GO professional, Robin "<strong>ScrunK</strong>" Röpke, to take the reigns as the team's coach, the organization announced Wednesday. </p><figure><blockquote class="twitter-tweet" lang="en"><p lang="en" dir="ltr">We would like to officially welcome #CSTScrunK as our new CS:GO coach! Please show your support and give him a follow!!</p>— Team Coast (#TeamCoastGaming) September 30, 2015</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></figure><p>"I would like to thank Team Coast and the players for giving me this opportunity to throw my EU knowledge and style into the NA scene," said ScrunK in his statement to HLTV.org. "I am excited to see where this route in my career leads me and where I can help this team go."</p><p>Team Coast are currently competing in the North American divisions of both CEVO-P Season 8 and ESL ESEA Pro League Season 2. They currently sit at sixth in the CEVO-P division with a 2-4-3 record and third in the ESL ESEA Pro League with a record of 3-4.</p><p><em>Paul Park is a writer for theScore eSports. <a target="_blank" href="https://twitter.com/phjpark">You can follow him on Twitter</a>.</em></p><p><small><em>Copyright © 2015 Score Media Ventures Inc. All rights reserved. Certain content reproduced under license.</em></small></p>]]>
</content:encoded>
<link rel="related" type="text/html" href="http://www.thescoreesports.com/news/4070" title="Dead Pixels CS:GO part ways with FARIS and YOUNS"/>
<link rel="related" type="text/html" href="http://www.thescoreesports.com/news/4115" title="G2.Kinguin add jkaem to roster"/>
<link rel="related" type="text/html" href="http://www.thescoreesports.com/news/4102" title="ESL ESEA Pro League Hot Match of week 3"/>
<link rel="related" type="text/html" href="http://www.thescoreesports.com/news/4061" title="HIGHLIGHT: azr shuts down Winterfox"/>
<link rel="related" type="text/html" href="http://www.thescoreesports.com/news/4063" title="DreamHack Stockholm Group B Roundup: Down and out"/>
</item>
Related
Am loading some blog data from a database with title and body but the body contains some HTML and CSS codes like the following below in the JSON data
{[News_Body: "<span style=\"color: black;\">The Lagos State Local Government
Election Appeal Tribunal have received 22 Appeals from the July
22 council polls in Lagos State.<br />\n <br />\n The
Chairperson of the 2017 Local Government Election Appeal
Tribunal, Justice G. M Onyeabo, stated this today 25th of
October at the tribunal's inaugural sitting. <br />\n <br
/>\n The tribunal had earlier been inaugurated on the 23 of
October, 2017 pursuant to Section 7 of the Local Government
Election Tribunal Law 2008, will hear and determine the appeals
in 21 days.<br />\n <br />\n Justice Onyeabo and four other
justices: O. Kasali, A. Onigbanjo, O.A Dabiri and K. A Jose make
up the panel.<br />\n <br />"
News_Title: "PRESS RELEASE - LAGOS LG ELECTION APPEAL TRIBUNAL RECEIVES 22
APPEALS"
Posted_By: "Ololade Ige"
Posted_Date: "10/31/2017 12:00:00 AM"], ...}
The problem I have is taking the body and summarizing its contents. I tried the following but it did not work as expected.
using CSS
.truncate {
height: 200px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Loading the data dynamically with javascript because it is coming from database
var p = document.createElement('p');
p.setAttribute('style', 'text-align:center; color: #ffffff !important;');
p.setAttribute('class', 'truncate');
var newSum = summary.split('<br />');;
p.innerHTML = newSum[0];
but the problem with the above is that not all object.News_Body contains a line break <br />. I don't have control as to how the data is stored, I just process what am given. Sadly :(
If jQuery is an option you could achieve something very quickly using the text function and some string manipulation.
var text = $("<div>" + content.News_Body + "</div>").text().substring(0, 3) + "..."
Just replace the 3 with your max content length. So substring(0, 10) will show 10 characters etc...
EDIT:
Using the link that #FMK posted at Strip HTML from Text JavaScript it would look like:
var text = strip("<div>" + content.News_Body + "</div>").substring(0, 3) + "..."
Which is a non-jquery option too.
I combined the two replies and I did this.
var p = document.createElement('p');
p.setAttribute('style', 'text-align:center; color: #ffffff !important;');
p.setAttribute('class', '');// removed my css truncate style class
var s = strip(summary).substring(0, 300) + "...";
p.innerHTML = s;
I got the strip function from Strip HTML from Text JavaScript
Thanks for the quick replies. You guys are awsome!!
I am trying to parse an RSS feed into an array but the feed is adding CDATA tags and combining certain elements.
My code below parses through the rss feed (url) and adds certain elements to an array. However when I look at the feed itself, it is combining multiple key elements in CDATA tags.
How do I parse through the CDATA tags to get usable xml fields?
Code
buildXMLDoc = function (url) {
var list =[];
$(listXML).find('item').each(function (){
var el = $(this);
console.log(el.find("title").text());
console.log(el.find("pubDate").text());
console.log(el.find("description").text());
list.push({title: el.find("title").text(), description: el.find("description").text(), modified: el.find("pubDate").text()});
});
return list;
};
XML
<?xml version="1.0" encoding="UTF-8"?>
<!--RSS generated by Microsoft SharePoint Foundation RSS Generator on 8/29/2017 10:23:18 AM -->
<?xml-stylesheet type="text/xsl" href="/_layouts/RssXslt.aspx?List=43aaf08e-0153-4f1d-9b46-e66bba563fde" version="1.0"?>
<rss version="2.0">
<channel>
<title>Webdocs: Test</title>
<description>RSS feed for the Test list.</description>
<lastBuildDate>Tue, 29 Aug 2017 14:23:18 GMT</lastBuildDate>
<generator>Microsoft SharePoint Foundation RSS Generator</generator>
<ttl>60</ttl>
<language>en-US</language>
<item>
<title>Alternative Methods for Determining LCRs</title>
<description><![CDATA[<div><b>Short Title:</b> Determining LCRs</div>
<div><b>Description:</b> <div class="ExternalClass6280076BC79848078688B86006BA554F"><p><span style="font-size:11.5pt;font-family:"calibri", "sans-serif"">This project is a carryover from the 2017 effort to identify an alternative method for calculating the Locational Minimum Installed Capacity Requirements (LCRs). </span></p></div></div>
<div><b>Governance Process Status:</b> Progress</div>
<div><b>Topic State:</b> Open/Current</div>
<div><b>Updated Placeholder:</b> updated</div>
]]></description>
<pubDate>Wed, 12 Jul 2017 13:41:06 GMT</pubDate>
</item>
The highlighted items are suppose to be separate elements.
In order to get the CDATA part details I may suggest to use jquery.contents() and so getting the relative sub sections by positon. This may give you wrong results if the positions change but it's a possibility.
var listXML = '<?xml version="1.0" encoding="UTF-8"?>\
<!--RSS generated by Microsoft SharePoint Foundation RSS Generator on 8/29/2017 10:23:18 AM -->\
<?xml-stylesheet type="text/xsl" href="/_layouts/RssXslt.aspx?List=43aaf08e-0153-4f1d-9b46-e66bba563fde" version="1.0"?>\
<rss version="2.0">\
<channel>\
<title>Webdocs: Test</title>\
<description>RSS feed for the Test list.</description>\
<lastBuildDate>Tue, 29 Aug 2017 14:23:18 GMT</lastBuildDate>\
<generator>Microsoft SharePoint Foundation RSS Generator</generator>\
<ttl>60</ttl>\
<language>en-US</language>\
<item>\
<title>Alternative Methods for Determining LCRs</title>\
<description><![CDATA[<div><b>Short Title:</b> Determining LCRs</div>\
<div><b>Description:</b> <div class="ExternalClass6280076BC79848078688B86006BA554F"><p><span style="font-size:11.5pt;font-family:"calibri", "sans-serif"">This project is a carryover from the 2017 effort to identify an alternative method for calculating the Locational Minimum Installed Capacity Requirements (LCRs). </span></p></div></div>\
<div><b>Governance Process Status:</b> Progress</div>\
<div><b>Topic State:</b> Open/Current</div>\
<div><b>Updated Placeholder:</b> updated</div>\
]]></description>\
<pubDate>Wed, 12 Jul 2017 13:41:06 GMT</pubDate>\
</item>';
var list =[];
$(listXML).find('item').each(function (){
var el = $(this);
var cdat = $(listXML).find('item description').contents();
console.log(cdat.eq(1).text() + cdat.eq(2).text());
console.log(cdat.eq(5).contents().eq(0).text() + cdat.eq(5).contents().eq(1).text());
console.log(cdat.eq(6).contents().eq(0).text() + cdat.eq(6).contents().eq(1).text());
list.push({title: cdat.eq(2).text(), description: cdat.eq(5).contents().eq(1).text(), modified: cdat.eq(6).contents().eq(1).text()});
});
console.log('list: ' + JSON.stringify(list));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A different approach is to get the description element, replace the inner CDATA and convert the result to a jQuery object. On this object you can use find in order to select sub elements.
var listXML = '<?xml version="1.0" encoding="UTF-8"?>\
<!--RSS generated by Microsoft SharePoint Foundation RSS Generator on 8/29/2017 10:23:18 AM -->\
<?xml-stylesheet type="text/xsl" href="/_layouts/RssXslt.aspx?List=43aaf08e-0153-4f1d-9b46-e66bba563fde" version="1.0"?>\
<rss version="2.0">\
<channel>\
<title>Webdocs: Test</title>\
<description>RSS feed for the Test list.</description>\
<lastBuildDate>Tue, 29 Aug 2017 14:23:18 GMT</lastBuildDate>\
<generator>Microsoft SharePoint Foundation RSS Generator</generator>\
<ttl>60</ttl>\
<language>en-US</language>\
<item>\
<title>Alternative Methods for Determining LCRs</title>\
<description><![CDATA[<div><b>Short Title:</b> Determining LCRs</div>\
<div><b>Description:</b> <div class="ExternalClass6280076BC79848078688B86006BA554F"><p><span style="font-size:11.5pt;font-family:"calibri", "sans-serif"">This project is a carryover from the 2017 effort to identify an alternative method for calculating the Locational Minimum Installed Capacity Requirements (LCRs). </span></p></div></div>\
<div><b>Governance Process Status:</b> Progress</div>\
<div><b>Topic State:</b> Open/Current</div>\
<div><b>Updated Placeholder:</b> updated</div>\
]]></description>\
<pubDate>Wed, 12 Jul 2017 13:41:06 GMT</pubDate>\
</item>';
var list =[];
$(listXML).find('item').each(function (){
var el = $(this);
var cdat = $(listXML).find('item description').contents();
var html = $($(listXML).find('item description')[0].innerHTML.replace('<!--[CDATA[', '')).html();
console.log(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a strange problem. In general, when I set a variable as textContent, it shows it, but it doesn't when I set it as innerHTML
More precisely
Here is the HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Dynamic Menu</title>
</head>
<body id="top">
<h1>The Extremadura Region of Western Spain</h1>
<h2 >Geography Of The Region</h2>
<p>The autonomous community of Extremadura is in western Spain alongside the Portuguese border.
It borders the Spanish regions of Castilla y Leon, Castilla La Mancha and Andalucía as well as Portugal (to the West).
Covering over 40,000 square kilometers it has two provinces: Cáceres in the North and Badajoz in the South.</p>
<h2>Where To Stay</h2>
<p>There is a wide range of accommodation throughout Extremadura including small inns and guest houses ('Hostals') or
think about renting a 'casa rural' (country house) if you are travelling in a group.</p>
<h2>Climate</h2>
<p>Generally Mediterranean, except for the north, where it is continental. Generally known for its extremes,
including very hot and dry summers with frequent droughts, and its long and mild winters.</p>
<h2>What To See</h2>
<p>Extremadura hosts major events all year round including theater, music, cinema, literature and folklore.
Spectacular venues include castles, medieval town squares and historic centers.
There are special summer theater festivals in the Mérida, Cáceres, Alcántara and Alburquerque.</p>
<h2>Gastronomy</h2>
<p>The quality of Extremaduran food arises from the fine quality of the local ingredients.
In addition to free-range lamb and beef, fabulous cheeses, red and white wines, olive oil, honey and paprika,
Extremadura is particularly renowned for Iberian ham. The 'pata negra' (blackfoot) pigs are fed on acorns in the
cork-oak forests, the key to producing the world's best ham and cured sausages.</p>
<script src="lunch.js"></script>
</body>
</html>
Here is the script
function lop(){
var hs = document.getElementsByTagName('h2');
for(var g = 0; g<hs.length; g++){
hs[g].setAttribute('id', g);
}
var budy = document.getElementById('top'); //Gets the body id
var nnn = document.createElement('nav'); //Creats a nav event
var uuu = "<ul > \
<li id='one'> <a href='#0'>Geography Of The Region </a> </li> \
<li id='two'> <a href='#1'>Where To Stay </a> </li> \
<li id='tre'> <a href='#2'>Climate </a> </li> \
<li id='for'> <a href='#3'>What To See</a> </li> \
<li id='fiv'> <a href='#4'>Gastronomy</a> </li>";
// li: 55-60 make the HTML
nnn.innerHTML = uuu; //Sets the HTML to the nav
var h = document.getElementsByTagName('h2')[0]; // Get the specific element
budy.insertBefore(nnn, h); // inserts the element nav and the whole html before h
var ps = document.getElementsByTagName('p');
var hih = ' AAAAA ';
for(var g = 0; g<ps.length; g++){
ps[g].nextSibling.innerText = hih;
}
}
lop(); //cals the function so it executes
So basicly in this exercise i have to create an ul within the script and without modyfing the HTML.
I successed in creating an ul. Then I have to creat a link that brings me to the top of the page. Which is this part here:
var ps = document.getElementsByTagName('p');
var hih = ' AAAAA ';
for(var g = 0; g<ps.length; g++){
ps[g].nextSibling.innerText = hih;
}
Here I try to creat a link that bring me back to the top. Im using the advantage that chrome has blank space betwwen sibling to creat that link in there.
The problem is that it doesn't show. When I go to my debugger, I have no errors, but nothings shows. If change ps[g].nextSibling.innerText = hih; for .textContent it shows the whole think.
I know the difference between .innerHTML and .textContent (or I think), so why doesn't it show my link and can I make it show ?
I don't understand you use nextSibling. If you want to use innerHTML, you can use bellow script
ps[g].innerHTML = ps[g].innerHTML + hih;
You can read about nextSibling in https://www.w3schools.com/jsref/prop_node_nextsibling.asp
Ok so a friend of mine changed my procedure and here what he did:
var ps = document.getElementsByTagName('p');
var hih = '<br /><br /> To the top ';
for(var g = 0; g<ps.length; g++) {
ps[g].innerHTML += hih;
}
In other words, what I learned from this 3h of js, is that you can't change a blank child's HTML, but only his text.
Once again I humbly come before you with bruises upon my head from beating my head against a wall...
I have been trying to learn as I go in figuring out how to populate a jQuery EasyUI accordion from a php/MySQL query. I believe that I am now getting the data back to the webpage correctly, but I am unable to figure out how to parse and format this to be displayed as the content on the page. What I am attempting to achieve is basically an accordion to display the contact history with each correspondence with an individual as an accordion item. Here is a sample of the output from the PHP query.
{"rows":[{"phone":"5554072634","contact_dt":"2014-01-27 22:51:37","method":"Email","who":"Scott","note":""},{"phone":"5554072634","contact_dt":"2014-01-27 23:08:49","method":"Spoke","who":"Scott","note":"Called back and she is not interested."}]}
I am trying to get the "contact_dt" as the title of each accordion tab and then format the rest of the elements in the body of the accordion tabs. Currently I'm getting a busy spinner when I select the Contact History tab that contains the accordion but this only yields a tiny square box in the body and does not alter the title. Here is the code that I'm sure I have mangled. First for the HTML portion...
<div id="history" title="Prospect Contact History" closable="true" style="padding:10px;">
<h2 class="atitle">Prospect Details</h2>
<div id="aa" class="easyui-accordion" style="width:500px;height:300px;">
<div title="Title1" data-options="iconCls:'icon-save'" style="overflow:auto;padding:10px;">
<h3 id="hist_title" style="color:#0099FF;">Accordion for jQuery</h3>
<p>Accordion is a part of easyui framework for jQuery.
It lets you define your accordion component on web page more easily.</p>
</div>
</div>
</div>
Now for the jQuery pieces... First is the JS to basically call the function. This is in the body at the end of the page.
<script type="text/javascript">
$('#tt').tabs({
onSelect:function(title){
if (title == 'Prospect Contact History'){
//$( "#hist_title" ).html( "Accordion function is working.");
accordionHistory();
}
}
});
</script>
Now for the function that is defined in the head and where I think the real mess is at.
function accordionHistory() {
$( "#hist_title" ).html( "Accordion function is working.");
var pp = $('#aa').accordion('getSelected'); // get the selected panel
if (pp){
pp.panel('refresh','contact_history.php?phone=' + phone); // call 'refresh' method to load new content
var temp = $('#aa').form('load',pp);
$.each( temp, function( i, val ) {
var txt1=$("<p>Time: ").html(val.contact_dt);
var txt2=$("</p><p>Method: ").html(val.method);
var txt3=$("</p><p>Who: ").html(val.who);
var txt4=$("</p><p>Note: ").html(val.note);
//$("#hist_title").html(val.contact_dt);
$("#hist_item").html(txt2,txt3,txt4);
});
}
}
I'm sure I'm displaying gross ignorance here in basic JS concepts. As I mentioned at the beginning I'm really using this as a learning exercise as well as building something useful. Any help would be greatly appreciated. Additionally, any online tutorials that might help walk me thru some of my conceptual shortcomings would be most welcome. Thanks in advance.
Well... I finally have figured out my issues. Here is the function that I'm now using to get this working.
function accordionHistory() {
var pp = $('#aa').accordion('getSelected'); // get the selected panel
if (pp){
$.ajax({
post: "GET",
url: "get_history.php?phone=" + phone,
dataType: 'json',
success: function( details ) {
$.each(details.rows, function(index, element) {
$('#hist_title').replaceWith(
'Phone: '
+ element.phone
+ 'Contact time: '
+ this.contact_dt
+ '<br/>Method: '
+ this.method
+ '<br/>Who: '
+ this.who
+ '<br/>Note: '
+ this.note
);
});
}
});
}
}
I hope some other noob like myself finds this useful.
I need to parse an RSS feed (XML version 2.0) and display the parsed details in an HTML page.
Parsing the Feed
With jQuery's jFeed
(Don't really recommend that one, see the other options.)
jQuery.getFeed({
url : FEED_URL,
success : function (feed) {
console.log(feed.title);
// do more stuff here
}
});
With jQuery's Built-in XML Support
$.get(FEED_URL, function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
With jQuery and the Google AJAX Feed API
$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(FEED_URL),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});
But that means you're relient on them being online and reachable.
Building Content
Once you've successfully extracted the information you need from the feed, you could create DocumentFragments (with document.createDocumentFragment() containing the elements (created with document.createElement()) you'll want to inject to display your data.
Injecting the content
Select the container element that you want on the page and append your document fragments to it, and simply use innerHTML to replace its content entirely.
Something like:
$('#rss-viewer').append(aDocumentFragmentEntry);
or:
$('#rss-viewer')[0].innerHTML = aDocumentFragmentOfAllEntries.innerHTML;
Test Data
Using this question's feed, which as of this writing gives:
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:re="http://purl.org/atompub/rank/1.0">
<title type="text">How to parse a RSS feed using javascript? - Stack Overflow</title>
<link rel="self" href="https://stackoverflow.com/feeds/question/10943544" type="application/atom+xml" />
<link rel="hub" href="http://pubsubhubbub.appspot.com/" />
<link rel="alternate" href="https://stackoverflow.com/q/10943544" type="text/html" />
<subtitle>most recent 30 from stackoverflow.com</subtitle>
<updated>2012-06-08T06:36:47Z</updated>
<id>https://stackoverflow.com/feeds/question/10943544</id>
<creativeCommons:license>http://www.creativecommons.org/licenses/by-sa/3.0/rdf</creativeCommons:license>
<entry>
<id>https://stackoverflow.com/q/10943544</id>
<re:rank scheme="http://stackoverflow.com">2</re:rank>
<title type="text">How to parse a RSS feed using javascript?</title>
<category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="javascript"/><category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="html5"/><category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="jquery-mobile"/>
<author>
<name>Thiru</name>
<uri>https://stackoverflow.com/users/1126255</uri>
</author>
<link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript" />
<published>2012-06-08T05:34:16Z</published>
<updated>2012-06-08T06:35:22Z</updated>
<summary type="html">
<p>I need to parse the RSS-Feed(XML version2.0) using XML and I want to display the parsed detail in HTML page, I tried in many ways. But its not working. My system is running under proxy, since I am new to this field, I don't know whether it is possible or not. If any one knows please help me on this. Thanks in advance.</p>
</summary>
</entry>
<entry>
<id>https://stackoverflow.com/questions/10943544/-/10943610#10943610</id>
<re:rank scheme="http://stackoverflow.com">1</re:rank>
<title type="text">Answer by haylem for How to parse a RSS feed using javascript?</title>
<author>
<name>haylem</name>
<uri>https://stackoverflow.com/users/453590</uri>
</author>
<link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript/10943610#10943610" />
<published>2012-06-08T05:43:24Z</published>
<updated>2012-06-08T06:35:22Z</updated>
<summary type="html"><h1>Parsing the Feed</h1>
<h3>With jQuery's jFeed</h3>
<p>Try this, with the <a href="http://plugins.jquery.com/project/jFeed" rel="nofollow">jFeed</a> <a href="http://www.jquery.com/" rel="nofollow">jQuery</a> plug-in</p>
<pre><code>jQuery.getFeed({
url : FEED_URL,
success : function (feed) {
console.log(feed.title);
// do more stuff here
}
});
</code></pre>
<h3>With jQuery's Built-in XML Support</h3>
<pre><code>$.get(FEED_URL, function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
</code></pre>
<h3>With jQuery and the Google AJAX APIs</h3>
<p>Otherwise, <a href="https://developers.google.com/feed/" rel="nofollow">Google's AJAX Feed API</a> allows you to get the feed as a JSON object:</p>
<pre><code>$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(FEED_URL),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});
</code></pre>
<p>But that means you're relient on them being online and reachable.</p>
<hr>
<h1>Building Content</h1>
<p>Once you've successfully extracted the information you need from the feed, you need to create document fragments containing the elements you'll want to inject to display your data.</p>
<hr>
<h1>Injecting the content</h1>
<p>Select the container element that you want on the page and append your document fragments to it, and simply use innerHTML to replace its content entirely.</p>
</summary>
</entry></feed>
Executions
Using jQuery's Built-in XML Support
Invoking:
$.get('https://stackoverflow.com/feeds/question/10943544', function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
Prints out:
------------------------
title : How to parse a RSS feed using javascript?
author :
Thiru
https://stackoverflow.com/users/1126255
description:
------------------------
title : Answer by haylem for How to parse a RSS feed using javascript?
author :
haylem
https://stackoverflow.com/users/453590
description:
Using jQuery and the Google AJAX APIs
Invoking:
$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('https://stackoverflow.com/feeds/question/10943544'),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});
Prints out:
------------------------
title : How to parse a RSS feed using javascript?
author : Thiru
description: undefined
------------------------
title : Answer by haylem for How to parse a RSS feed using javascript?
author : haylem
description: undefined
Another deprecated (thanks to #daylight) option, and the easiest for me (this is what I'm using for SpokenToday.info):
The Google Feed API without using JQuery and with only 2 steps:
Import the library:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("feeds", "1");</script>
Find/Load feeds (documentation):
var feed = new google.feeds.Feed('http://www.google.com/trends/hottrends/atom/feed?pn=p1');
feed.load(function (data) {
// Parse data depending on the specified response format, default is JSON.
console.dir(data);
});
To parse data, check documentation about the response format.
If you are looking for a simple and free alternative to Google Feed API for your rss widget then rss2json.com could be a suitable solution for that.
You may try to see how it works on a sample code from the api documentation below:
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("https://news.ycombinator.com/rss");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(initialize);
<html>
<head>
<script src="https://rss2json.com/gfapi.js"></script>
</head>
<body>
<p><b>Result from the API:</b></p>
<div id="feed"></div>
</body>
</html>
If you want to use a plain javascript API, there is a good example at https://github.com/hongkiat/js-rss-reader/
The complete description at https://www.hongkiat.com/blog/rss-reader-in-javascript/
It uses fetch method as a global method that asynchronously fetches a resource. Below is a snap of code:
fetch(websiteUrl).then((res) => {
res.text().then((htmlTxt) => {
var domParser = new DOMParser()
let doc = domParser.parseFromString(htmlTxt, 'text/html')
var feedUrl = doc.querySelector('link[type="application/rss+xml"]').href
})
}).catch(() => console.error('Error in fetching the website'))
For anyone else reading this (in 2019 onwards) unfortunately most JS RSS reading implementations don't now work. Firstly Google API has shut down so this is no longer an option and because of the CORS security policy you generally cannot now request RSS feeds cross-domains.
Using the example on https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options (2015) I get the following:
Access to XMLHttpRequest at 'https://feeds.feedburner.com/raymondcamdensblog?format=xml' from origin 'MYSITE' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is correct and is a security precaution by the end website but does now mean that the answers above are unlikely to work.
My workaround will probably be to parse the RSS feed through PHP and allow the javascript to access my PHP rather than trying to access the end-destination feed itself.
I was so exasperated by many misleading articles and answers that I wrote my own RSS reader:
https://gouessej.wordpress.com/2020/06/28/comment-creer-un-lecteur-rss-en-javascript-how-to-create-a-rss-reader-in-javascript/
You can use AJAX requests to fetch the RSS files but it will work if and only if you use a CORS proxy. I'll try to write my own CORS proxy to give you a more robust solution. In the meantime, it works, I deployed it on my server under Debian Linux.
My solution doesn't use JQuery, I use only plain Javascript standard APIs with no third party libraries and it's supposed to work even with Microsoft Internet Explorer 11.
You can use jquery-rss or Vanilla RSS, which comes with nice templating and is super easy to use:
// Example for jquery.rss
$("#your-div").rss("https://stackoverflow.com/feeds/question/10943544", {
limit: 3,
layoutTemplate: '<ul class="inline">{entries}</ul>',
entryTemplate: '<li>[{author}#{date}] {title}<br/>{shortBodyPlain}</li>'
})
// Example for Vanilla RSS
const RSS = require('vanilla-rss');
const rss = new RSS(
document.querySelector("#your-div"),
"https://stackoverflow.com/feeds/question/10943544",
{
// options go here
}
);
rss.render().then(() => {
console.log('Everything is loaded and rendered');
});
See http://jsfiddle.net/sdepold/ozq2dn9e/1/ for a working example.
Trying to find a good solution for this now, I happened upon the FeedEk jQuery RSS/ATOM Feed Plugin that does a great job of parsing and displaying RSS and Atom feeds via the jQuery Feed API. For a basic XML-based RSS feed, I've found it works like a charm and needs no server-side scripts or other CORS workarounds for it to run even locally.
I did not find a solution for parsing RSS just with js due to CORS error I kept receiving. Installing a plugin is not an option for me and building a proxy is not fun either and the small solutions I found didn't work.
So just in case someone is getting here and can use server-side, I found this solution in PHP that worked for me perfectly! (without the CORS error! "x has been blocked by CORS policy...")