skip to Main Content

I’m very new to JS, I’m trying to link two collections. I’m trying to make it so if an HTML element is a certain color, the parent HTML element will be clicked. If anyone could give any advice it would be greatly appreciated 🙂

const heart = document.querySelectorAll(".col > div > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1)");
const faheart = document.querySelectorAll(".fa-heart");

faheart.forEach(function(y, i) {
  const m = y.getAttribute("color");

  heart.forEach(function(z, i) {

    if (m != "#E3170A") {
      setTimeout(() => {
        z.click();
      }, i * 1000)
    };
  });
});

I tried mapping and using getters, I’m quite new so I couldn’t figure anything out unfortunately. What I’m currently getting is one of the elements just logging the other 24 times.

2

Answers


  1. Chosen as BEST ANSWER

    document.querySelectorAll(".clickable").forEach(el => {
      el.addEventListener('click', () => { alert('Clicked'); });
    });
    
    const faheart = document.querySelectorAll(".fa-heart");
    
    faheart.forEach(y => {
      const m = y.getAttribute("color");
      const z = y.parentNode;
      if (m != "#E3170A") {
        setTimeout(() => {
          z.click();
        }, 1000)
      }
    });
    <div class="col">
      <div>
        <div></div>
        <div>
          <div>
            <div>
              <div class="clickable">
                <div class="fa-heart" color="#E3170B"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>


  2. You don’t need nested loops. Check the colors and access the parent:

    document.querySelectorAll(".clickable").forEach(el => {
      el.addEventListener('click', () => { alert('Clicked'); });
    });
    
    const faheart = document.querySelectorAll(".fa-heart");
    
    faheart.forEach(y => {
      const m = y.getAttribute("color");
      const z = y.parentNode;
      if (m != "#E3170A") {
        setTimeout(() => {
          z.click();
        }, 1000)
      }
    });
    <div class="col">
      <div>
        <div></div>
        <div>
          <div>
            <div>
              <div class="clickable">
                <div class="fa-heart" color="#E3170B"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search