PTeam
PTeam

Reputation: 35

Adding string within a P element in Javascript

Not sure how to do this. Expected output is:

<p data-rating="3" class="starability-result">

Actual output:

<p is="data-rating="3"" class="starability-result">

Here is the code I have where 'review.rating' is the rating (1-5) returned in json.

const rating = document.createElement('p', `data-rating="${review.rating}"`);
rating.className = 'starability-result';
rating.innerHTML = `Rated: ${review.rating} stars`;
li.appendChild(rating);

Upvotes: 0

Views: 41

Answers (1)

Barmar
Barmar

Reputation: 780869

You can't provide attributes as an argument to document.createElement(), you need to do that as a separate step.

const rating = document.createElement('p');
rating.className = 'starability-result';
rating.dataset.rating = review.rating; // or rating.setAttribute("data-rating", review.rating);
rating.innerHTML = `Rated: ${review.rating} stars`;
li.appendChild(rating);

Upvotes: 3

Related Questions