英文:
Accessing class name in a innerHtml made in js file
问题
I am currently creating a cart with local storage.
When I add my products one by one, in the cart page, I do it with innerHtml:
productsContainer.innerHTML += `
<div class="cart-product">
<img src="../images/${item.tag}" alt="image product" style="height: 120px;">
<div class="product-info-container">
<div class="product-cross"><i class="bi bi-x"></i></div>
<div class="product-info">
<h4 class="product-title">${item.name}</h4>
<h5 class="price">${item.inCart * item.price} €</h5>
<div class="product-info-number">
<i class="bi bi-dash" id="bi-dash"></i>
<span class="quantity">${item.inCart}</span>
<i class="bi bi-plus" id="bi-plus"></i>
</div>
</div>
</div>
</div>
`
The problem I have now is that I want to access my two icons (i class="bi-dash / i class="bi-plus") to increase and decrease the quantity. I tried to store them in variables with querySelector and getElementById but it doesn't work. I get a null error.
英文:
I am currently creating a cart with local storage.
When I add my products one by one, in the cart page, I do it with innerHtml :
productsContainer.innerHTML += `
<div class="cart-product">
<img src="../images/${item.tag}" alt="image product" style="height: 120px;">
<div class="product-info-container">
<div class="product-cross"><i class="bi bi-x"></i></div>
<div class="product-info">
<h4 class="product-title">${item.name}</h4>
<h5 class="price">${item.inCart * item.price} €</h5>
<div class="product-info-number">
<i class="bi bi-dash" id="bi-dash"></i>
<span class="quantity">${item.inCart}</span>
<i class="bi bi-plus" id="bi-plus"></i>
</div>
</div>
</div>
</div>
`
The problem I have now is that I want to access my two icons (i class="bi-dash / i class="bi-plus") to increase and decrease the quantity. I tried to store them in variables with querySelctore and getElementById but it doesn't work. I get a null error.
答案1
得分: 1
看起来工作正常。
以下是在控制台中记录的元素示例:
<html>
<body>
<div id="test"></div>
<script>
let testElement = document.getElementById("test");
testElement.innerHTML += `
<i class="bi bi-dash" id="bi-dash">bi-dash</i>
<i class="bi bi-plus" id="bi-plus">bi-plus</i>
`;
let biDash = document.getElementById("bi-dash");
let biPlus = document.getElementById("bi-plus");
console.log(test, biDash, biPlus);
</script>
</body>
</html>
希望这对您有帮助。
英文:
Seems to work fine.
Here's a snippet showing the elements being logged in the console:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<html>
<body>
<div id="test"></div>
<script>
let testElement = document.getElementById("test");
testElement.innerHTML += `
<i class="bi bi-dash" id="bi-dash">bi-dash</i>
<i class="bi bi-plus" id="bi-plus">bi-plus</i>
`;
let biDash = document.getElementById("bi-dash");
let biPlus = document.getElementById("bi-plus");
console.log(test, biDash, biPlus);
</script>
</body>
</html>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论