skip to Main Content

how to write a function for checking the presence of an element with a certain id.
I have these IDs for verification set in an array:
let CartArray = ["cart-0", "cart-1", "cart-2", "cart-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");
            }
          }
        });
      });

the code doesn’t fit in stackoverflow, so I’m adding a link to codepen:
https://codepen.io/SHvari_David_Simba/pen/JjBNXzp

I tried to check the presence of the item by the id from the array, but nothing happened

3

Answers


  1. This might suit your need.

    function hasDocumentElementById(id){
      return !!document.getElementById(id); // returns boolean
    }
    
    Login or Signup to reply.
  2. /**
     * 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)
    }
    
    Login or Signup to reply.
  3. You can use myelement.querySelector('[id="' + id + '"]') to search children by 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search