trebek1 trebek1 - 3 months ago 12
HTML Question

Dynamic HTML Tag generated from JavaScript, two-word class not working

I am trying to create dynamic html from an api response. Whenever I get a two-word class name, I cannot get it to save both words as the string is ending when it see's the space. See below:

for(var i = 0; i<articles.posts.length; i++){
var cls = 'fa '+articles.posts[i].category;
var el = "<article><i class="+cls+"></i><h2> From the Archive </h2><h1> " + articles.posts[i].title + "</h1><h3> " + articles.posts[i].date + " </h3><p> " + articles.posts[i].blurb + "</p></article>"

$("#article-list").last().append(el);
}


For Instance if 'cls' is fa fa-space-shuttle, the class gets set as 'fa' not both 'fa fa-space-shuttle'. Any idea how to get around this using javascript?

Answer

Whenever I get a two-word class name

There are no two-word class names. What you have there is two classes.

var el = "<article><i class="+cls+"></i><h2> From the Archive </h2><h1> " + articles.posts[i].title + "</h1><h3> " + articles.posts[i].date + " </h3><p> " + articles.posts[i].blurb + "</p></article>"

Look closely at the quotes in that line of code. There aren't any around the class attribute. So, according to the HTML specification, the value ends at the first space. Add quotes around it:

var el = "<article><i class='"+cls+"'></i><h2> From the Archive </h2><h1> " + articles.posts[i].title + "</h1><h3> " + articles.posts[i].date + " </h3><p> " + articles.posts[i].blurb + "</p></article>"
// -------------------------^-------^

Example:

var cls = "fa fa-link";
var el = "<article><i class='"+cls+"'></i><h2> From the Archive </h2></article>"
document.body.insertAdjacentHTML("beforeend", el);
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>

Comments