jquery 如何写一个函数来检查元素html的存在[duplicate]

wbgh16ku  于 2023-01-12  发布在  jQuery
关注(0)|答案(3)|浏览(87)
    • 此问题在此处已有答案**:

Is there an "exists" function for jQuery?(47个答案)
20小时前关门了。
如何编写一个函数来检查某个id的元素是否存在。我在一个数组中设置了这些id来进行验证:令车数组=["车-0","车-1","车-2","车-3"];
JavaScript语言:

//=== === === Cart === === ===\\
      $(document).ready(function() {
        //========= checking the presence of items in the cart when the page is loaded =========\\
        if(document.getElementById('myDIV').childElementCount == 0) {
          document.getElementById('myDIV').innerHTML = "cart is empty";
        }
        
        const element = document.getElementById('myDIV');
        const numberOfChildren = element.childElementCount; //====== Number of items in the cart

        //========= Changing ::before for the cart when the page is loaded =========\\
        for(var i = 0; i < numberOfChildren; i++) {
          CartCount++;
        }
        document.getElementById("CountCartS").setAttribute('CartCountS', CartCount);

        //========= Add to cart (number changes) =========\\
        $("#button-count").click(function () {
          CartCount++;
          document.getElementById("CountCartS").setAttribute('CartCountS', CartCount);
        });

        const button = document.querySelector('#button');
        
        button.addEventListener('click', function() {
          for(var i = 0; i < numberOfChildren; i++) {
            const parent = document.getElementById('myDIV');
            const child = parent.children[i];
            
            if(parent.childElementCount > 0) {
              if(child.id == CartArray[i]) {
                alert(child.id + " --- there is a div with this id");
              }
              else if(child.id != CartArray[i]) {
                alert(child.id + " --- does not have a div with that id");
              }
            }
            else if(parent.childElementCount == 0) {
              document.getElementById('myDIV').innerHTML = "cart is empty";
            }
            else {
              alert("Error");
            }
          }
        });
      });

代码不适合stackoverflow,所以我添加了一个到codepen的链接:https://codepen.io/SHvari_David_Simba/pen/JjBNXzp
我尝试通过数组中的id检查该项是否存在,但没有任何结果

mgdq6dx1

mgdq6dx11#

您可以使用myelement.querySelector('[id="' + id + '"]')按id搜索子项:

let CartArray = ["cart-0", "cart-1", "cart-2", "cart-3"];

function isChildExists(parent)
{
  for(let i = 0; i < CartArray.length; i++)
  {
    if (parent.querySelector('[id="' + CartArray[i] + '"]'))
      return true;
  }
  return false;
}

function check(el)
{
  el.dataset.exists = isChildExists(el.parentNode);
}
[id]::before
{
  content: attr(id) " " attr(data-exists);
}
<div><button id="cart-0" onclick="check(this)"></button></div>
<div><button id="cart-1" onclick="check(this)"></button></div>
<div><button id="cart-2" onclick="check(this)"></button></div>
<div><button id="cart-3" onclick="check(this)"></button></div>
<div><button id="cart-4" onclick="check(this)"></button></div>
4jb9z9bj

4jb9z9bj2#

这可能适合你的需要。

function hasDocumentElementById(id){
  return !!document.getElementById(id); // returns boolean
}
myzjeezk

myzjeezk3#

/**
 * Get existing id 
 *
 * @param {Array} ids List of id 
 * @returns An array of existing id
 */
function getExistingIds(ids) {
  return ids.filter(id => document.getElementById(id) ? true : false)
}

/**
 * Check id existence
 * 
 * @param {Array} ids List of id 
 * @returns An array of boolean, true if id is exist, and false if it's not 
 */
function checkIds(ids) {
  return ids.map(id => document.getElementById(id) ? true : false)
}

相关问题