Search code examples
javascripthtmltumblr

How can I make this JavaScript code display the post title?


I am using the Tumblr Badge script to embed my Tumblr feed on my website. Originally, there was no post title support so I added this code.

postTitle = document.createElement("h3");
postTitle.className = "tumblr-post-title";
postTitle.innerHTML = post["regular-title"];
listItem.appendChild(postTitle);

This will display the post title, but on posts without titles it displays "undefined" instead. Is there some way to fix this? Thanks


Solution

  • If "regular-title" isn't a property of post, it will return undefined. An easy, quick fix is to return an empty string if so:

    postTitle.innerHTML = post["regular-title"] || "";
    

    This will check to see if post["regular-title"] is a truthy value (not any of these: false, 0, NaN, undefined, "", null). If it's truthy, it will set the innerHTML with post["regular-title"]...otherwise with the "".