Reputation: 294
I am trying to disseminate the values over a repetitive property to set the contents of certain nodes. The way I'm doing it is effective. However, as I've mentioned, it's repetitive and kind of frustrating to look at. Is there any other way to shorten my codes?
for (var i = 0; i < 1; i++) {
var title = document.querySelector("h1.title"),
date = document.querySelector(".article-date"),
tme = document.querySelector(".article-tme"),
src = document.querySelector(".source"),
user = document.querySelector(".user"),
tip = document.querySelector(".tip");
//.....some other variables...
title.innerHTML = post[i].titles;
date.innerHTML = post[i].dates;
src.innerHTML = post[i].sources;
tme.innerHTML = post[i].times;
user.innerHTML = post[i].authors;
tip.innerHTML = post[i].excerpts;
//....some other HTML content setting...
}
...where "post" = JSON.parse(this.response);
Any kind of help to shorten this burden is appreciated. Thank you.
Upvotes: 2
Views: 126
Reputation: 371049
I'd use an object that maps the property names to selectors:
const selectorsByProp = {
titles: 'h1.title',
dates: '.article-date',
sources: '.source',
// ...
}
Object.entries(selectorsByProp).forEach(([prop, selector]) => {
document.querySelector(selector).innerHTML = post[i][prop];
});
Note that if the object values happen to contain plain text only, it would make a lot more sense to assign to the textContent
of the element, rather than the innerHTML
:
document.querySelector(selector).textContent = post[i][prop];
There's no need for the loop either, since you're just doing this once.
Upvotes: 1