简体   繁体   English

如何使用 JavaScript 检查另一个元素内是否有一个元素

[英]How to check if there's an element inside another element with JavaScript

The main idea is: I have a list of beverage in a div and I'd like to check if the beverages are out of stock or not , and click the first drink available in stock.主要思想是:我在div中有一个beverage清单,我想check饮料是否out of stock or not ,然后click第一个有货的first drink available It needs to be in JavaScript (without JQuery)它需要在JavaScript 中(不带 JQuery)

The elements are in this hierarchy :元素位于此hierarchy中:

Main div containing all the drinks: class="ob-menu-items__items"包含所有饮料的Main divclass="ob-menu-items__items"

Each drink will be in a H4 class="ob-menu-item__title" Each drink都属于H4 class="ob-menu-item__title"

If the product is out of stock there will be a span class="ob-menu-item__out-of-stock" with the text " - Out of Stock"如果产品out of stock ,会有一个span class="ob-menu-item__out-of-stock"带有text " - Out of Stock"

So far I try this (and got stuck):到目前为止,我尝试了这个(并被卡住了):

for (var i = 0; i < 7; i++) {
    // iterating over each drink.
    var drink = document.getElementsByClassName("ob-menu-item__title")[i];
    if (document.getElementsByClassName(".ob-menu-item__out-of-stock").parents(drink).length == 1) {
        // There's out of stock text
        // Do nothing and go to the next drink 
    } else {
        //The product is available. Clik the drink and exit the loop
        document.getElementsByClassName("ob-menu-item__title")[i].click();
        break;
    }
} 

Thanks!谢谢!

Replace your if condition as below and it will work as expected.如下替换您的if条件,它将按预期工作。 It will find elements inside drinks which has class ob-menu-item__out-of-stock .它将在具有 class ob-menu-item__out-of-stock drinks中找到elements

if (drink.getElementsByClassName("ob-menu-item__out-of-stock").length > 0)

Please refer this answer which says .getElementsByClassName("home")[0] should not be used.请参考这个答案,其中说.getElementsByClassName("home")[0]不应使用。 You can alternatively use .querySelectorAll() like below.您也可以使用.querySelectorAll() ,如下所示。 Replace getElementsByClassName with querySelectorAll and pass class name with class selector (.) .getElementsByClassName替换为querySelectorAll并使用class selector (.)传递class name So document.getElementsByClassName("ob-menu-item__title")[i] will be replaced with document.querySelectorAll(".ob-menu-item__title")[i] .所以document.getElementsByClassName("ob-menu-item__title")[i]将被替换为document.querySelectorAll(".ob-menu-item__title")[i]

To find elements inside selected element you can use element.querySelectorAll which is done inside if with drink.querySelectorAll(".ob-menu-item__out-of-stock").length要在selected元素中查找elements ,您可以使用element.querySelectorAll ,它在if with drink.querySelectorAll(".ob-menu-item__out-of-stock").length内部完成

for (var i = 0; i < 7; i++) {
    // iterating over each drink.
    var drink = document.querySelectorAll(".ob-menu-item__title")[i];
    if (drink.querySelectorAll(".ob-menu-item__out-of-stock").length > 0) {
        // There's out of stock text
        // Do nothing and go to the next drink 
    } else {
        //The product is available. Clik the drink and exit the loop
        drink.click();
        break;
    }
}

Try it below.在下面试试。

 // get all drink var drinks = document.querySelectorAll(".ob-menu-item__title"); // iterating over each drink. for (var i = 0; i < drinks.length; i++) { let drink = drinks[i]; if (drink.querySelectorAll(".ob-menu-item__out-of-stock").length > 0) { console.log('out of stock. i = ' + i); // There's out of stock text // Do nothing and go to the next drink } else { //The product is available. Clik the drink and exit the loop console.log('In stock. i = ' + i); drink.click(); break; } }
 <div class='ob-menu-items__items'> <h4 class='ob-menu-item__title'> item0<span class='ob-menu-item__out-of-stock'> - Out of stock</span> </h4> <h4 class='ob-menu-item__title'> item4<span class='ob-menu-item__out-of-stock'> - Out of stock</span> </h4> <h4 class='ob-menu-item__title'> item2<span class='ob-menu-item__out-of-stock'> - Out of stock</span> </h4> <h4 class='ob-menu-item__title'> item3 </h4> <h4 class='ob-menu-item__title'> item4 </h4> <h4 class='ob-menu-item__title'> item5 </h4> <h4 class='ob-menu-item__title'> item6 </h4> </div>

You could use childElementCount to find how many items there are.您可以使用childElementCount来查找有多少项目。 See https://www.w3schools.com/jsref/prop_element_childelementcount.asphttps://www.w3schools.com/jsref/prop_element_childelementcount.asp

for (var i = 0; i < 7; i++) {
    var drink = document.getElementsByClassName("ob-menu-item__title")[i];
    if (document.getElementsByClassName.("ob-menu-item__out-of-stock").parents(drink).length == 1) {
        // There's out of stock text
        // Do nothing and go to the next drink 
    } else {
        //The product is available. Clik the drink and exit the loop
        document.getElementsByClassName("ob-menu-item__title")[i].click();
        break;
    }
}

The hard-coded 7 in the for loop initialization doesn't look good. for 循环初始化中硬编码的7看起来不太好。 You can just find all the drinks by document.querySelectorAll and then find the one to click by checking for the span in each of them.您可以通过document.querySelectorAll找到所有饮料,然后通过检查每个饮料的跨度来找到要单击的饮料。

ES6 one-liner: ES6 单行:

[...document.querySelectorAll('.ob-menu-item__title')]
  .find( drink => !drink.querySelector('.ob-menu-item__out-of-stock') )
  .click()

What it does is: converts the querySelectorAll result into an Array, then uses Array.prototype.find method which returns the first element that satisfied the callback, and the call back in this case returns true if given element doesn't contain the "out of stock" span.它的作用是:将querySelectorAll结果转换为数组,然后使用Array.prototype.find方法返回满足回调的第一个元素,如果给定元素不包含“out”,则在这种情况下,回调返回true库存”跨度。

More "classic" JS:更多“经典”JS:

var firstInStock = Array.from(document.querySelectorAll('.ob-menu-item__title'))
  .find( function(drink){
    if( drink.querySelector('.ob-menu-item__out-of-stock') ){
      return false;
    }
    return true;
  });
firstInStock.click()

Or if you really want a for loop:或者如果你真的想要一个 for 循环:

var drinks = document.querySelectorAll('.ob-menu-item__title');
for(var i=0; i< drinks.length; i++){
   if( !drink.querySelector('.ob-menu-item__out-of-stock') ){
     drink.click();
     break;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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