I'm trying to pull thumbnail URLs from a wordpress feed and keep getting [object HTMLCollection] instead of an image URL string for the thumbnail. The feed i'm pulling from is: https://harpercollegece.com/feed/. I know that the tag is named media:thumbnail and the value is stored in 'URL'. I can't find the correct way to reference this image inside of the forEach loop when running through each post. I've tried searching other posts as well as on google for several hours.
var proxy = 'https://api.allorigins.win/raw?url=';
var feeds = [
'https://harpercollegece.com/feed/',
];
var limit = 10;
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
function strip_tags(string) {
if ((string === null) || (string === '')) {
return '';
} else {
string = string.toString();
}
string = string.replace('<![CDATA[', '');
string = string.replace(' […]]]>', '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(']]>', '');
return string;
}
function get_rss(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300) {
var response = xhr.responseText;
var parser = new window.DOMParser();
var data = parser.parseFromString(response, "text/xml");
var items = Array.from(data.querySelectorAll("item"));
var output = '';
forEach(items, function(index, item) {
if (index <= limit) {
var ilink = item.querySelector("link").innerHTML;
var title = item.querySelector("title").innerHTML;
var descr = item.querySelector("description").innerHTML;
var thumb = item.getElementsByTagName("media:thumbnail");
//console.log(item);
output +=
'<div class="ce-blog-slider-well">' +
'<div class = "ce-blog-thumb">' +
'<img class="blog-post-img" src="' + thumb + '" alt="Veterans Center Sign">' +
'</div>' +
'<div class = "ce-blog-header">' +
'' + strip_tags(title) + '' +
'</div>' +
'<div class ="ce-blog-descr">' + strip_tags(descr) + '</div>' +
'</div>';
}
});
var d1 = document.getElementById('wp-blog-posts');
d1.insertAdjacentHTML("beforeend", output);
}
};
xhr.open('GET', url);
xhr.send();
}
forEach(feeds, function(index, feed) {
get_rss(proxy + encodeURIComponent(feed));
});
<div class="ce-blog-slider" id="wp-blog-posts"></div>
getElementsByTagName returns an HTMLCollection. To get the URL, you'll have to grab the first element in that collection with [0]. The URL is stored in an attribute called url, a la
<media:thumbnail url="https://harpercollegece.files.wordpress.com/2021/01/writing-red-typewriter-typing.jpg" />
From your HTMLElement, get the url attribute like so:
var thumb = item.getElementsByTagName("media:thumbnail")[0].getAttribute("url");
var proxy = 'https://api.allorigins.win/raw?url=';
var feeds = [
'https://harpercollegece.com/feed/',
];
var limit = 10;
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
function strip_tags(string) {
if ((string === null) || (string === '')) {
return '';
} else {
string = string.toString();
}
string = string.replace('<![CDATA[', '');
string = string.replace(' […]]]>', '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(']]>', '');
return string;
}
function get_rss(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300) {
var response = xhr.responseText;
var parser = new window.DOMParser();
var data = parser.parseFromString(response, "text/xml");
var items = Array.from(data.querySelectorAll("item"));
var output = '';
forEach(items, function(index, item) {
if (index <= limit) {
var ilink = item.querySelector("link").innerHTML;
var title = item.querySelector("title").innerHTML;
var descr = item.querySelector("description").innerHTML;
var thumb = item.getElementsByTagName("media:thumbnail")[0].getAttribute("url");
//console.log(item);
output +=
'<div class="ce-blog-slider-well">' +
'<div class = "ce-blog-thumb">' +
'<img class="blog-post-img" src="' + thumb + '" alt="Veterans Center Sign">' +
'</div>' +
'<div class = "ce-blog-header">' +
'' + strip_tags(title) + '' +
'</div>' +
'<div class ="ce-blog-descr">' + strip_tags(descr) + '</div>' +
'</div>';
}
});
var d1 = document.getElementById('wp-blog-posts');
d1.insertAdjacentHTML("beforeend", output);
}
};
xhr.open('GET', url);
xhr.send();
}
forEach(feeds, function(index, feed) {
get_rss(proxy + encodeURIComponent(feed));
});
<div class="ce-blog-slider" id="wp-blog-posts"></div>
Related
How do i show all the data by using the loop to display all the data from json to html ?
ATM , I am able to print one of the data. but if i am using data[i] the code will not display any data.
I think I mess up the the concept of object and array.
please advice me , how to loop thru object , like array?
thanks
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET','https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data.weather ){
var x= data.weather[i].main;
weatherString+= "<p class='weather'>" + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
to get all data check for object and do recursive loop
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
//console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data) {
var x = data[i];
if(typeof(x) == "object") {
getHTML(x);
}
else {
weatherString += "<p class='weather'><b>" + i + "</b>: " + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for (var i in data.weather) {
var x = data.weather[i].main;
weatherString += "<p class='weather'>" + x + "</p>";
$.each(data.main, function(i, f) {
var main = "<div>" + i + ": " + f + "</div>";
$(main).appendTo("#main");
});
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
<div id="main"></div>
use foreach loop to iterate over all object
read more from here
I am creating some html tag and assigning data as below.
MyCombo = function(args) {
var dataUrl = args.url;
var divID = args.divID;
var div = document.getElementById(divID);
var myTable = '<input type="text" id="myInput" list="myUL" onclick = "MyList()" onkeyup="MyList()" style="width:100% " >' +
'<ul id="myUL" hidden=false>' + '<li>' + '<a href="#" ></a>' + '</li>' + '</ul>';
div.innerHTML = myTable;
function getData(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', dataUrl, true);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
callback(httpRequest.responseText);
}
};
httpRequest.send();
}
getData(function(data) {
var jsonc = JSON.parse(data);
var new_opt = "";
for (i = 0; i < jsonc.length; i++) {
new_opt += '<li>' + jsonc[i]['VALUE'] + '</li>';
}
document.getElementById('myUL').innerHTML = new_opt;
});
}
Now when I pass my second div, previous data is getting lost. And for first div I am getting second data.
This how I am calling the class :
For the first instance
var myCombo = new liveSearch({
"url": "data1.json",
"divID": "ID1",
});
For the second instance
var myCombo2 = new liveSearch({
"url": "data2.json",
"divID": "ID2",
});
Any idea how to overcome this?
In getData you call
document.getElementById('myUL').innerHTML = new_opt;
which writes to the element called myUL everytime it is called.
Append instead of replacing
document.getElementById('myUL').appendChild(new_opt);
or you can append to the old
old_html = document.getElementById('myUL').innerHTML;
document.getElementById('myUL').innerHTML = old_html+new_opt;
I am working on Address book using HTML,CSS and Javascript. First I am reading some data entries from a JSON file. Then storing those entries into local storage. Then I am taking input from the user in few input fields through the function called addToBook(). And then storing all the data in JSON format in the variable called addressBook. But when i am trying to print this data in the function called showaddressBook(). It is not happening as it is showing as Undefined in the chrome console. Refer to this line(console.log(addressBook[i].practice_name);) in the function showaddressBook(). Any idea guys. Thanks in advance.
window.onload = function(){
var quickAddFormDiv = document.querySelector('.quickaddForm');
var AddBtn = document.getElementById('Add');
// Form Fields
var lastname = document.getElementById('lastname');
var firstname = document.getElementById('firstname');
var email = document.getElementById('email');
var specialty = document.getElementById('specialty');
var practicename = document.getElementById('practicename');
// Divs etc.
var addBookDiv = document.querySelector('.addbook');
var addressBook = [];
var people;
localStorage.clear();
//--------------------------------------------------------------------
//To display the contents of JSON file
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
people = response.people;
//var output = "";
var str1 = '';
for(var i = 0; i <people.length;i++){
str1 += '<div id="entry">';
str1 += '<div id="name"><p>' + people[i].last_name +', '+people[i].first_name+ '</p></div>';
str1 += '<div id="email"><p>' + people[i].email_address + '</p></div>';
str1 += '<div id="practicename"><p>' + people[i].practice_name + '</p></div>';
str1 += '<div id="specialty"><p>' + people[i].specialty + '</p></div>';
str1 += '<div id="del">Delete</div>';
}
for(var i = 0; i < people.length;i++){
var obj = new jsonStructure(people[i].last_name,people[i].first_name,people[i].email_address,people[i].specialty,people[i].practice_name);
addressBook.push(obj);
localStorage['addbook'] = JSON.stringify(addressBook);
}
document.getElementsByClassName("addbook")[0].innerHTML = str1;
}
};
xhttp.open("GET", "people.json", true);
xhttp.send();
//------------------------------------------------------------------------------
AddBtn.addEventListener("click", addToBook);
//var addressBook = [];
addBookDiv.addEventListener("click", removeEntry);
function jsonStructure(lastname,firstname,email,specialty,practicename){
this.lastname = lastname;
this.lastname += ", "+firstname;
this.email = email;
this.specialty = specialty;
this.practicename = practicename;
}
function addToBook(){
var isNull = lastname.value!='' && firstname.value!='' && email.value!='' && specialty.value!='' && practicename.value!='';
if(isNull){
// format the input into a valid JSON structure
var obj = new jsonStructure(lastname.value,firstname.value,email.value,specialty.value,practicename.value);
addressBook.push(obj);
localStorage['addbook'] = JSON.stringify(addressBook);
console.log(localStorage['addbook']);
clearForm();
showaddressBook();
}
}
function removeEntry(e){
// Remove an entry from the addressBook
if(e.target.classList.contains('delbutton')){
var remID = e.target.getAttribute('data-id');
addressBook.splice(remID,1);
localStorage['addbook'] = JSON.stringify(addressBook);
showaddressBook();
}
}
function clearForm(){
var formFields = document.querySelectorAll('.formFields');
for(var i in formFields){
formFields[i].value = '';
}
}
function showaddressBook(){
if(localStorage['addbook'] === undefined){
localStorage['addbook'] = '';
} else {
addressBook = JSON.parse(localStorage['addbook']);
addBookDiv.innerHTML = '';
var str = '';
for(var i = 0; i <addressBook.length;i++){
str += '<div id="entry">';
str += '<div id="name"><p>' + addressBook[i].last_name +', '+addressBook[i].first_name+ '</p></div>';
str += '<div id="email"><p>' + addressBook[i].email_address + '</p></div>';
str += '<div id="practicename"><p>' + addressBook[i].practice_name + '</p></div>';
str += '<div id="specialty"><p>' + addressBook[i].specialty + '</p></div>';
str += '<div id="del">Delete</div>';
console.log(addressBook[i].practice_name);
}
}
}
showaddressBook();
}
There are typo mistakes,
practice_name should be practicename
last_name should be lastname
first_name should be firstname
email_address should be email
Try:
for(var i = 0; i <addressBook.length;i++){
str += '<div id="entry">';
str += '<div id="name"><p>' + addressBook[i].lastname +', '+addressBook[i].firstname+ '</p></div>';
str += '<div id="email"><p>' + addressBook[i].email + '</p></div>';
str += '<div id="practicename"><p>' + addressBook[i].practicename + '</p></div>';
str += '<div id="specialty"><p>' + addressBook[i].specialty + '</p></div>';
str += '<div id="del">Delete</div>';
console.log(addressBook[i].practicename);
}
I am trying to insert pictures to id "pokedex-view" by using Ajax GET. I think "spriteurl" is showing the correct path. But does not work correctly, and it cannot find the pciture for the local folder. Is there something wrong in this code. Thanks.
function populatePokedex() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all");
xhr.onload = function(){
if (this.status == 200) {
var picArr = this.responseText.split("\n");
for(var i=0; i < picArr.length; i++){
var eachName = picArr[i].split(":")
var spriteurl = "/Pokedex/sprites/" + eachName[1];
document.getElementById("pokedex-view").innerHTML += spriteurl
document.getElementById("pokedex-view").innerHTML += "<img src = spriteurl>";
}
} else {
document.getElementById("pokedex-view").innerHTML = "ERROR: Status: " + this.status + ", " + this.statusText;
}
}
xhr.onerror = function(){
document.getElementById("pokedex-view").innerHTML = "ERROR";
}
xhr.send();
}
Try to concatenate or to interpolate the way you assign the spriteurl as the src attribute:
document.getElementById("pokedex-view").innerHTML += '<img src="' + spriteurl + '">'
Or:
document.getElementById("pokedex-view").innerHTML += `<img src="${spriteurl}">`
Sorry for the poor title–I didn't know what to put.
Anyways, I have this object I want to loop thru in order to dynamically output some icons onclick:
<button id="btn">hit me</button>
var socialMedia = {
facebook: "http://facebook.com",
twitter: "http://twitter.com",
instagram: "http://instagram.com",
dribbble: "http://dribbble.com",
social: function() {
var output = "<ul>";
var myList = document.querySelectorAll('.socialSpot');
for (var key in arguments[0]) {
output += '<li><a href="' + this[key] + '"><img src="_assets/'
+ key + '.png" alt="' + key + 'icon"></a></li>';
}
output += '</ul>';
for (var i = myList.length - 1; i >= 0; i--) {
myList[i].innerHTML = output;
};
}
};
var theBtn = document.getElementById('btn');
theBtn.addEventListener('click', function() {
socialMedia.social(socialMedia);
}, false);
I know I could remove the method and instantiate it while passing the object, but I was wondering how I could go about it this way. In other words, I want to leave the function as a method of the socialMedia {}. Any pointers?
Just add a if (typeof obj[key] != "string") continue; test to your loop:
…
social: function(obj) {
var output = "<ul>";
var myList = document.querySelectorAll('.socialSpot');
for (var key in obj) {
if (typeof this[key] != "string") continue;
output += '<li><a href="' + this[key] + '"><img src="_assets/'
+ key + '.png" alt="' + key + 'icon"></a></li>';
}
output += '</ul>';
for (var i = myList.length - 1; i >= 0; i--) {
myList[i].innerHTML = output;
};
}
Of course, simply using another object would be so much cleaner:
var socialMedia = {
data: {
facebook: "http://facebook.com",
twitter: "http://twitter.com",
instagram: "http://instagram.com",
dribbble: "http://dribbble.com"
},
social: function(obj) {
var data = obj || this.data;
var output = "<ul>";
for (var key in data) {
output += '<li><a href="' + data[key] + '"><img src="_assets/'
+ key + '.png" alt="' + key + 'icon"></a></li>';
}
output += '</ul>';
var myList = document.querySelectorAll('.socialSpot');
for (var i = myList.length - 1; i >= 0; i--) {
myList[i].innerHTML = output;
};
}
};
var theBtn = document.getElementById('btn');
theBtn.addEventListener('click', function() {
socialMedia.social();
}, false);
You don't need to pass in socialMedia to have access to the socialMedia object inside of the social function. As the social function's execution context is socialMedia's execution context, this will be bound to socialMedia inside of social. In other words
var socialMedia = {
...
social: function(){
var socialMedia = this;
//socialMedia.facebook == this.facebook
//socialMedia.twitter == this.twitter
//you can loop through this inside of for in to get these properties
//(although you may want to make sure to avoid the function again)
}
};
this will be available no matter what, so you can call socialMedia.social() without any arguments.
You could do it with an easier API and still keep both together (without having them both together)
var socialMedias = (function() {
var medias = {
facebook: "http://facebook.com",
twitter: "http://twitter.com",
instagram: "http://instagram.com",
dribbble: "http://dribbble.com",
};
return function(socials) {
if (!socials) {
return medias;
}
var output = "<ul>";
var myList = document.querySelectorAll('.socialSpot');
for (var key in socials) {
output += '<li><a href="' + this[key] + '"><img src="_assets/'
+ key + '.png" alt="' + key + 'icon"></a></li>';
}
output += '</ul>';
for (var i = myList.length - 1; i >= 0; i--) {
myList[i].innerHTML = output;
};
};
})();
So socialMedias() return the map, individual entry can be fetched like socialMedias().facebook and socialMedias(myArgument) would run the method