I am trying to make a div show/hide based on the content of another div. It’s a simple thing, but I am new to JS and I just can’t seem to figure it out. If the price is "Free", I want the "Dollar" To hide, if it’s any number whatsoever, I want it to show.
So we have multiple divs that contain the same thing.
if (document.getElementsByClassName("bookPrice") != null) {
var price = document.getElementsByClassName("price");
var priceTag = document.getElementsByClassName("priceTag");
if ((price.textContent = "Free")) {
priceTag.style.display = "none";
} else if (price.textContent != "Free") {
priceTag.style.display = "block";
}
}
<div class="priceParent">
<div class="priceTag">$</div>
<div class="price">Free</div>
</div>
<div class="priceParent">
<div class="priceTag">$</div>
<div class="price">60</div>
</div>
There’s multiple instances of it, and I want them to react according to their own div, not as a whole.
Any help is greately appreciated. Thank you.
3
Answers
I think the issue might be your variables. See, you had defined the price variable as: document.getElementsByClassName("price"), the variable will be turned into a list, as your code told the program to grab multiple items. Because of this, the way you wrote your if statement, it’s checking the price variable as if it were a regular variable, not a list. What you may be able to do to fix this is adding a for loop that goes through all of the items in price list, and checking the index of each one for an equivalent value of "Free." This could work.
You can do something like this:
getElementsByClassName()
returns an array-like list that you’d need to iterate over in order to interact with each element. A similar function isquerySelectorAll()
, and here’s an example of how to access the items that are selected: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll#accessing_the_matchesThe notable difference between the results of these 2 functions is that
getElementsByClassName
returns a live HTMLCollection, whilequerySelectorAll
returns a static NodeList.I also adjusted the
display
property to display the tag/price next to each other, and I added another class to toggle this via a CSS class rather than an inline style.