Pull Image Url From RSS FEED - javascript

I'm using the following code to display to parse an RSS feed via Javascript and Google Feed API into HTML. Is it possible to grab an image from the RSS feed? It is working fine fro the title, snippet, date and link. I just need the URL for the image as well.
function myGetElementsByClassName(selector) {
if ( document.getElementsByClassName ) {
return document.getElementsByClassName(selector);
}
var returnList = new Array();
var nodes = document.getElementsByTagName('div');
var max = nodes.length;
for ( var i = 0; i < max; i++ ) {
if ( nodes[i].className == selector ) {
returnList[returnList.length] = nodes[i];
}
}
return returnList;
}
var rssReader = {
containers : null,
// initialization function
init : function(selector) {
containers = myGetElementsByClassName(selector);
for(i=0;i<containers.length;i++){
// getting necessary variables
var rssUrl = containers[i].getAttribute('rss_url');
var num = containers[i].getAttribute('rss_num');
var id = containers[i].getAttribute('id');
// creating temp scripts which will help us to transform XML (RSS) to JSON
var url = encodeURIComponent(rssUrl);
var googUrl = 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num='+num+'&q='+url+'&callback=rssReader.parse&context='+id;
var script = document.createElement('script');
script.setAttribute('type','text/javascript');
script.setAttribute('charset','utf-8');
script.setAttribute('src',googUrl);
containers[i].appendChild(script);
}
},
// parsing of results by google
parse : function(context, data) {
var container = document.getElementById(context);
container.innerHTML = '';
// creating list of elements
var mainList = document.createElement('ul');
// also creating its childs (subitems)
var entries = data.feed.entries;
for (var i=0; i<entries.length; i++) {
var listItem = document.createElement('li');
var title = entries[i].title;
var publishedDate = entries[i]. publishedDate;
var contentSnippet = entries[i].contentSnippet;
var contentSnippetText = document.createTextNode(contentSnippet);
var mediaGroup = entries[i].mediaGroup;
var link = document.createElement('a');
link.setAttribute('href', entries[i].link);
link.setAttribute('target','_blank');
var text = document.createTextNode(title);
link.appendChild(text);
var text = document.createTextNode(publishedDate);
link.appendChild(text);
var text = document.createTextNode(mediaGroup);
link.appendChild(text);
// add link to list item
listItem.appendChild(link);
var desc = document.createElement('p');
desc.appendChild(contentSnippetText);
// add description to list item
listItem.appendChild(desc);
// adding list item to main list
mainList.appendChild(listItem);
}
container.appendChild(mainList);
}
};
window.onload = function() {
rssReader.init('post_results');
}
<div class="post_results" id="post_results2" rss_num="2" rss_url="http://www.feed.com/feed">
<div class="loading_rss">
<img alt="Loading..." src="images/loading.gif" />
</div>
</div>

I was able to pull the content (which houses the image tag) with: var
content = entries[i].content;
And parse that to get just the image using this:
var input = content;
var div = document.createElement('div');
div.innerHTML = input;
var img = div.getElementsByTagName('img')[0];

Related

How do you send a list of a node's children ids using thymeleaf?

I have a function that adds badges to a div by selecting items from a dropdown list.
I'm adding badges using this function added to the dropdown list onclick event:
function addBadge(parent, badgeId, value){
var elem = document.getElementById(parent);
var currentTaxiways = elem.children;
var alreadyExists = false;
for(var i = 0; i < currentTaxiways.length; i++){
if(badgeId === currentTaxiways[i].id){
alreadyExists = true;
}
}
if(!alreadyExists) {
var newBadge = document.createElement("span");
newBadge.classList.add("badge");
newBadge.classList.add("badge-primary");
newBadge.classList.add("bg-secondary");
newBadge.id = badgeId;
var node = document.createTextNode(value);
newBadge.appendChild(node);
newBadge.innerHTML += " ";
var deleteButton = document.createElement("a");
deleteButton.href = "#";
deleteButton.classList.add("x-btn");
deleteButton.onclick = function delBadge() {
deleteBadge(newBadge.id);
};
var node2 = document.createTextNode("X");
deleteButton.appendChild(node2);
newBadge.appendChild(deleteButton);
elem.appendChild(newBadge);
}
}
And the function for deleting the badges is this one:
function deleteBadge(badge){
var elem = document.getElementById(badge);
elem.parentNode.removeChild(elem);
}
How do I send the list of ids of all the badges added to the div to my controller using thymeleaf when the form is submitted?

How to get the index of a string in google docs using google App Script

I want to search for a string and then replace it with an image on google docs. For that, I want to get the index of the string and then replace it with an image. But I'm unable to get the index of the string so far.
Below is a snippet of what I am doing:
var element = '<<19>>';
options = {muteHttpExceptions: true};
var resp = UrlFetchApp.fetch(mylist[x-1], options);
var image = resp.getBlob();
//getting the index of element and then replacing it with image
var rangeElement = body.findText(element);
var foundElement = rangeElement.getStartOffset();
body.replaceText(element, body.insertImage(foundElement, image));
I've tried using findText(searchPattern) but it didn't work as it returns a range element and I'm getting output as 0 everytime.
This is how you find text on your document and replace it with an image:
function findAndReplaceWithImage() {
var element = "<<19>>";
var doc = DocumentApp.getActiveDocument().getBody();
var image = "your image url";
var blob = UrlFetchApp.fetch(image).getBlob();
var paragraphs = doc.getParagraphs();
for (var i = 0; i < paragraphs.length; i++) {
var text = paragraphs[i].getText();
if (text === element) {
//Found your match
doc.removeChild(paragraphs[i]);
doc.insertImage(i, blob);
}
}
}
Hope this helps!

TypeError: Cannot read property "length" from undefined variables

I have worked with code that pulls table information off a site and then places into Google Sheets. While this had worked great for months, it has come to my attention that is has randomly stopped working.
I am getting the message "TypeError: Cannot read property "length" from undefined." From code:
for (var c=0; c<current_adds_array.length; c++) {
I have done extensive searching but cannot come to conclusion as to what is wrong.
Full code seen here:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Get Data')
.addItem('Add new dispatch items','addNewThings')
.addToUi();
}
function addNewThings() {
// get page
var html = UrlFetchApp.fetch("#").getContentText();
// bypass google's new XmlService because html isn't well-formed
var doc = Xml.parse(html, true);
var bodyHtml = doc.html.body.toXmlString();
// but still use XmlService so we can use getDescendants() and getChild(), etc.
// see: https://developers.google.com/apps-script/reference/xml-service/
doc = XmlService.parse(bodyHtml);
var html = doc.getRootElement();
// a way to dig around
// Logger.log(doc.getRootElement().getChild('form').getChildren('table'));
// find and dig into table using getElementById and getElementsByTagName (by class fails)
var tablecontents = getElementById(html, 'formId:tableExUpdateId');
// we could dig deeper by tag name (next two lines)
// var tbodycontents = getElementsByTagName(tablecontents, 'tbody');
// var trcontents = getElementsByTagName(tbodycontents, 'tr');
// or just get it directly, since we know it's immediate children
var trcontents = tablecontents.getChild('tbody').getChildren('tr');
// create a nice little array to pass
var current_adds_array = Array();
// now let's iterate through them
for (var i=0; i<trcontents.length; i++) {
//Logger.log(trcontents[i].getDescendants());
// and grab all the spans
var trcontentsspan = getElementsByTagName(trcontents[i], 'span');
// if there's as many as expected, let's get values
if (trcontentsspan.length > 5) {
var call_num = trcontentsspan[0].getValue();
var call_time = trcontentsspan[1].getValue();
var rptd_location = trcontentsspan[2].getValue();
var rptd_district = trcontentsspan[3].getValue();
var call_nature = trcontentsspan[4].getValue();
var call_status = trcontentsspan[5].getValue();
//saveRow(call_num, call_time, rptd_location, rptd_district, call_nature, call_status);
current_adds_array.push(Array(call_num, call_time, rptd_location, rptd_district, call_nature, call_status));
}
}
saveRow(current_adds_array);
}
//doGet();
function saveRow(current_adds_array) {
// load in sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// find the current last row to make data range
var current_last_row = sheet.getLastRow();
var current_last_row_begin = current_last_row - 50;
if (current_last_row_begin < 1) current_last_row_begin = 1;
if (current_last_row < 1) current_last_row = 1;
//Logger.log("A"+current_last_row_begin+":F"+current_last_row);
var last_x_rows = sheet.getRange("A"+current_last_row_begin+":F"+current_last_row).getValues();
var call_num, call_time, rptd_location, rptd_district, call_nature, call_status;
// iterate through the current adds array
for (var c=0; c<current_adds_array.length; c++) {
call_num = current_adds_array[c][0];
call_time = current_adds_array[c][1];
rptd_location = current_adds_array[c][2];
rptd_district = current_adds_array[c][3];
call_nature = current_adds_array[c][4];
call_status = current_adds_array[c][5];
// find out if the ID is already there
var is_in_spreadsheet = false;
for (var i=0; i<last_x_rows.length; i++) {
//Logger.log(call_num+" == "+last_15_rows[i][0]);
if (call_num == last_x_rows[i][0] && call_time != last_x_rows[i][1]) is_in_spreadsheet = true;
}
Logger.log(is_in_spreadsheet);
//Logger.log(last_15_rows.length);
if (!is_in_spreadsheet) {
Logger.log("Adding "+call_num);
sheet.appendRow([call_num,call_time,rptd_location,rptd_district,call_nature,call_status]);
}
}
}
function getElementById(element, idToFind) {
var descendants = element.getDescendants();
for(i in descendants) {
var elt = descendants[i].asElement();
if( elt !=null) {
var id = elt.getAttribute('id');
if( id !=null && id.getValue()== idToFind) return elt;
}
}
}
function clearRange() {
//replace 'Sheet1' with your actual sheet name
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
sheet.getRange('A2:F').clearContent();}
function getElementsByTagName(element, tagName) {
var data = [];
var descendants = element.getDescendants();
for(i in descendants) {
var elt = descendants[i].asElement();
if( elt !=null && elt.getName()== tagName) data.push(elt);
}
return data;
}
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("C:C");
range.setValues(range.getValues().map(function(row) {
return [row[0].replace(/MKE$/, " Milwaukee, Wisconsin")];
}));
Please be careful when instantiating a new array. You are currently using var current_adds_array = Array(). You're not only missing the new keyword, but also, this constructor is intended to instantiate an Array with an Array-like object.
Try changing this to var current_adds_array = []

Bootstrap panels not displaying body text

For some reason my bootstrap panels won't show the body text. I have set up all my elements via DOM Manipulation.
My panel header text displays properly, however my body text doesn't show up.
I also noticed that the bootstrap panel body content does not have any elements, just lines of text.
I have tried to add text elements to it but so far nothing has been working. Here is my code:
JS
var searchButton = document.getElementById('search-button');
searchButton.addEventListener('click', function() {
var term = document.getElementById('term').value;
var matched = [];
for (var i = 0; i < hotelRooms.length; i++) {
if (hotelRooms[i].hotel.indexOf(term) !== -1) {
matched.push(hotelRooms[i]);
}
}
for (var i = 0; i < matched.length; i++) {
var roomResults = document.createElement('div');
roomResults.setAttribute('id', 'results');
roomResults.setAttribute('class', 'result-style');
var resultsArea = document.getElementById('results-area');
console.log(matched[i]);
var panelDefault = document.createElement('div');
panelDefault.setAttribute('class', 'panel-default');
var panelHeading = document.createElement('div');
panelHeading.setAttribute('class', 'panel-heading');
var panelBody = document.createElement('div');
panelBody.setAttribute('class', 'panel-body');
var name = document.createElement('h3'); // Hotel Name
name.setAttribute('class', 'hotel-name');
name.textContent = matched[i].hotel;
var price = document.createElement('div'); // Room Price
price.setAttribute('class', 'room-price');
price.textContent = matched[i].price;
roomResults.appendChild(panelDefault);
panelDefault.appendChild(panelHeading);
panelHeading.appendChild(name);
panelBody.appendChild(price);
resultsArea.appendChild(roomResults);
}
});
You are never appending panelBody to panelDefault.
....
roomResults.appendChild(panelDefault);
panelDefault.appendChild(panelHeading);
panelHeading.appendChild(name);
panelBody.appendChild(price);
panelDefault.appendChild(panelBody);
....
You have just created a div, you need to append it to the body tag document.body.appendChild(size)
var size = document.createElement('div');
size.setAttribute('class', 'room-size');
size.textContent ="hello"
document.body.appendChild(size)

Uncaught TypeError: Cannot read property '0' of undefined (Google Feed API)

I'm developing a Chrome extension and trying to add my website RSS Feed with images in the extension using Google Feed API.
But its throwing error
Uncaught TypeError: Cannot read property '0' of undefined
Here's the Script
function myGetElementsByClassName(selector) {
if ( document.getElementsByClassName ) {
return document.getElementsByClassName(selector);
}
var returnList = new Array();
var nodes = document.getElementsByTagName('div');
var max = nodes.length;
for ( var i = 0; i < max; i++ ) {
if ( nodes[i].className == selector ) {
returnList[returnList.length] = nodes[i];
}
}
return returnList;
}
var rssReader = {
containers : null,
// initialization function
init : function(selector) {
containers = myGetElementsByClassName(selector);
for(i=0;i<containers.length;i++){
// getting necessary variables
var rssUrl = containers[i].getAttribute('rss_url');
var num = containers[i].getAttribute('rss_num');
var id = containers[i].getAttribute('id');
// creating temp scripts which will help us to transform XML (RSS) to JSON
var url = encodeURIComponent(rssUrl);
var googUrl = 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num='+num+'&q='+url+'&callback=rssReader.parse&context='+id;
var script = document.createElement('script');
script.setAttribute('type','text/javascript');
script.setAttribute('charset','utf-8');
script.setAttribute('src',googUrl);
containers[i].appendChild(script);
}
},
// parsing of results by google
parse : function(context, data) {
var container = document.getElementById(context);
container.innerHTML = '';
// creating list of elements
var mainList = document.createElement('ul');
// also creating its childs (subitems)
var entries = data.feed.entries;
for (var i=0; i<entries.length; i++) {
var img = new Image();
img.src = entries[i].mediaGroups[0].contents[0].url;
listItem.appendChild(img);
var listItem = document.createElement('li');
var title = entries[i].title;
var contentSnippet = entries[i].contentSnippet;
var contentSnippetText = document.createTextNode(contentSnippet);
var link = document.createElement('a');
link.setAttribute('href', entries[i].link);
link.setAttribute('target','_blank');
var text = document.createTextNode(title);
link.appendChild(text);
// add link to list item
listItem.appendChild(link);
var desc = document.createElement('p');
desc.appendChild(contentSnippetText);
// add description to list item
// listItem.appendChild(desc);
// adding list item to main list
mainList.appendChild(listItem);
}
container.appendChild(mainList);
}
};
window.onload = function() {
rssReader.init('post_results');
}
<div class="post_results" id="post_results1" rss_num="4" rss_url="http://www.pixlov.com/feed">
<div class="loading_rss">
<img alt="Loading..." src="https://www.script-tutorials.com/demos/82/images/loading.gif" />
</div>
</div>
The Problem is with this line
img.src = entries[i].mediaGroups[0].contents[0].url;
But the weird Thing is that when I add Feed link of this website http://mightydeals.com/feed then it works!.
The issue is in feed url. the response of the feed url data not contains the mediaGroups property. So when your are trying to get the index 0 value from it, it's throwing 0 index error.
To resolve the issue first you need to check the response data contains the the mediaGroups key or not.
Like
if(entries[i].mediaGroups && entries[i].mediaGroups.length >0)

Categories

Resources