Skip to content
Advertisement

Unable to display JavaScript / jQuery div tag without dependency on another tag

I’m using JavaScript with jQuery to display my RSS Medium feed when there is a <div id="medium-feed"... on the page.

When the JSON data is pulled, I display the data using HTML, some CSS, and the bootstrap library with day.js (to format the date). So far it worked as expected (see code snippets at the bottom).

Preview of the Medium blog posts

I also want to display a more compact version of the feed to my footer that shows the title and published date. So I copied down my original code and have JavaScript look for a <div id="medium-feed-footer"... to display the other version of the feed so it can look like this:

Footer version of the latest blog posts

This only works if I show both of my div elements on the same page, like my blog page:

JavaScript

But if I visit any other page that only shows the footer version of my feed, it’s empty, as seen on my homepage. When you test out my code snippet, just add the -footer part in the ID on its own and it won’t show up. It looks like there is a dependency to show both div tags in order for it to work properly.

How can I have my footer version show up independently? I tried various ways such as breaking this code into two separate files and trying an if/then statement, but the result is always the same.

JavaScript
JavaScript
JavaScript

Advertisement

Answer

On other pages, Javascript doesn’t find an element with id = "medium-feed" so it returns an error. First, check if the element exists.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement