I am wondering how to target a specific element, knowing only its class.
I want to click the .editPrice button and only showing the .popupPriceContainer next to the button and not all of them.
The close button works fine since it is a child of the element I want to hide and I can easily target it with parentNode.
Here is a fiddle: https://jsfiddle.net/jwLf4smu/1/
And Here a runnable snippet:
//CLOSE POPUP PRICE CONTAINER
//create variable from pop up close buttons
const popupClose = document.getElementsByClassName('popupClose');
//set price edit container to display none
Array.from(popupClose).forEach((popupClose) => {
popupClose.addEventListener('click', () => {
// 2x .parentNode to select the outer wrapper
popupClose.parentNode.parentNode.style.display = "none";
});
});
//OPEN POPUP PRICE CONTAINER
//create variable for all edit price buttons and price edit pop up container
const popupEditPrice = document.getElementsByClassName('editPrice');
const priceContainer = document.getElementsByClassName('popupPriceContainer');
//show price edit box
Array.from(popupEditPrice).forEach((popupEditPrice) => {
popupEditPrice.addEventListener('click', () => {
Array.from(priceContainer).forEach((priceContainer) => {
priceContainer.style.display = "block";
});
});
});
#serviceList .position {
margin-top: 16px;
}
.popupPriceContainer {
display: none;
}
<section id="serviceList" class="items">
<div class="position">
<button type="button" class="editPrice">Edit price</button>
<div class="item">
Service 1
</div>
<div class="price">
<span class="amount" id="priceElement">100</span>
</div>
<div class="popupPriceContainer">
<div class="popupPriceInner">
<input type="number" placeholder="100,00" class="priceInput">
<button value="Set Value" class="submbitPrice popupClose">Submit</button>
<button class="popupClose">Close</button>
</div>
</div>
</div>
<div class="position">
<button type="button" class="editPrice">Edit price</button>
<div class="item">
Service 2
</div>
<div class="price">
<span class="amount">1000</span>
</div>
<div class="popupPriceContainer">
<div class="popupPriceInner">
<input type="number" placeholder="100,00" class="priceInput">
<button value="Set Value" class="submbitPrice popupClose">Submit</button>
<button class="popupClose">Close</button>
</div>
</div>
</div>
<div class="position">
<button type="button" class="editPrice">Edit price</button>
<div class="item">
Service 3
</div>
<div class="price">
<span class="amount">240</span>
</div>
<div class="popupPriceContainer">
<div class="popupPriceInner">
<input type="number" placeholder="100,00" class="priceInput">
<button value="Set Value" class="submbitPrice popupClose">Submit</button>
<button class="popupClose">Close</button>
</div>
</div>
</div>
</section>
e.target.closest('.popupPriceContainer')getElementsByClassNameanymore. In 2021 you should usequerySelectororquerySelectorAllinstead.