简体   繁体   中英

If class doesn't exist do this else ignore

Hi what I'm trying to do in Javascript is to find if a class '.promo' exists in the '.productDetails' div, if it does then no action needs to be taken, but if it doesn't exist then i want it to print the copy in the span tags. I know this can be done in jQuery but looking to do this in plain Javascript instead.

 var elem = document.querySelector('.product-details'); if(.elem.classlist.contains('.promo')){ document.querySelector('.title');innerHTML += "<span class="promo">Add Promo Banner</span>"; }
 .product-details {border: 1px black solid; margin: 10px 0}
 <div class="product-details"> <div class="title">Title</div> <div class="promo">Promo 20% off</div> </div> <div class="product-details"> <div class="title">Title</div> </div>

First of all, case matters in JS ( classlist != classList ), should be camel case classList . ALso, the htmlString ( "<span class="promo">Add Promo Banner</span>" ) is not properly formatted.

You can check the length by getting element with querySelectorAll() :

 var elem = document.querySelectorAll('.product-details'); elem.forEach(function(el){ if(.el.querySelectorAll('.promo').length){ el.querySelector('.title');innerHTML += "<span class=promo>Add Promo Banner</span>"; } });
 .product-details {border: 1px black solid; margin: 10px 0}
 <div class="product-details"> <div class="title">Title</div> <div class="promo">Promo 20% off</div> </div> <div class="product-details"> <div class="title">Title</div> </div>

As far as the JS, the issue in your code is just the syntax. The member is called

<HTML element>.classList

You're just missing the capitalized L.

elem.classList will not return ".classNameA.classNameB" , but rather the actual string value of the class attribute, like this: "classNameA classNameB"

But still, I do not believe that your code will behave properly if you make these changes, because you are searching an element for a class that it does not inherit from. The element that inherits from "promo" is a child element of the element you have a reference to.

The element you are looking for in your particular code is found in the elem.children array, which is iterable.

Are you trying to search all children of all elements on the page to find heirs of .classList containing "promo" ? If so, you should check out tree traversal algorithms. The more obvious implementations of this are that you would start at some root and navigate down via depth-first or breadth-first searching. The DOM is really just a giant tree of elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM