3

I'm currently practicing objects and properties using JavaScript. I tried inserting it in innerHTML but the desired output is displaying ${item.img} in string form instead of the actual image. I also tried separating the code in different lines in notepad++, but it is not recognized by the compiler unless it is typed in one line. Kindly advice solution for this.

Here is the JavaScript code:

const item = {};
item.img = 'img-cart${partPath}';
let name = event.target.parentElement.parentElement.nextElementSibling
                .children[0].children[0].textContent;
item.name = name;
let price = event.target.parentElement.parentElement.nextElementSibling
                .children[0].children[1].textContent;
let finalPrice = price.slice(1).trim();
item.price = finalPrice;

const cartItem = document.createElement("div");
cartItem.classList.add(
    "cart-item",
    "d-flex",
    "justify-content-between",
    "text-capitalize",
    "my-3"
);      

problem is here ----> cartItem.innerHTML = '<img src="${item.img}" class="img-fluid rounded-circle" id="item-img" alt=""><div class="item-text"><p id="cart-item-title" class="font-weight-bold mb-0">${item.name}</p><span>$</span><span id="cart-item-price" class="cart-item-price" class="mb-0">${item.price}</span></div><a href="#" id="cart-item-remove" class="cart-item-remove"><i class="fas fa-trash"></i></a></div>';

1 Answer 1

8

According to the syntax, Template Literals are enclosed by the back-tick (``). Since you are using single quote (' ') the whole string is treating as plain string, it is not evaluating the expression in it.

cartItem.innerHTML = `<img src="${item.img}" class="img-fluid rounded-circle" id="item-img" alt=""><div class="item-text"><p id="cart-item-title" class="font-weight-bold mb-0">${item.name}</p><span>$</span><span id="cart-item-price" class="cart-item-price" class="mb-0">${item.price}</span></div><a href="#" id="cart-item-remove" class="cart-item-remove"><i class="fas fa-trash"></i></a></div>`;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.