on my page I try to make a separation between bought and unsold products. The bought products uses the CSS class "winning_bid" in a . If this class is on a page I would like to hide another with the class "price". I would like to do something like the following structure in JS.
If CSS class "winning_bid" is on this page{ hide "price" }else display "winning_bid"}
Is this possible with JS. I need this case also for buttons. If CSS class "winning_bid" is in a div{ hide specific button in this div }else display button
Do you have any ideas?
CodePudding user response:
If you are willing to support newer browsers, there is the :has()
pseudo-class (which is relatively widely supported) that you can use:
body:has(.winning_bid) .price {
display: none;
}
<div >Winning bid</div>
<div>
<div>
<!-- This element can be nested at any level, it doesn't matter -->
<div >Price</div>
</div>
</div>
This method has the advantage over JS in the sense that if your page is somehow a SPA or its contents are dynamically updated, you need to use MutationObserver to constantly watch changes to the DOM in order to determine if the element .winning_bid
has been added to the document.
CodePudding user response:
In javascript way you can refer the below solution
<!DOCTYPE html>
<html>
<body>
<p>hide the elements if an item with class element is present</p>
<div ></div>
<div >Element1</div>
<div >Element2</div>
<script>
const element = document.getElementsByClassName("element");
if(element.length > 0){
const items = document.getElementsByClassName("example");
for (const item of items) {
item.style.display = 'none';
}
}
</script>
</body>
</html>
CodePudding user response:
I suppose you can use document.querySelector to check if there are any elements with the "winning_bid" class and get all the elements with the price class using querySelectorAll or getElementsByClassName an example of this would be
// querySelector returns null if there are no elements matching these selectors
if(document.querySelector(".winning_bid") != null) {
// get all elements with the price class if there are elements with winning_bid class
const elementsWithPriceClass = document.querySelectorAll(".price"){
// iterate over the NodeList (elementsWithPriceClass)
elementsWithPriceClass.forEach(element => {
// hide the element
element.style.display = "none"
})
}
}
I haven't tested this code but it should work in theory. Let me know about the results