Error when adding class to a node element

Asked

Viewed 50 times

0

My goal is: when clicking on the div "job-card", the respective "job-resume" should appear, but returns me the error "Uncaught Typeerror: Cannot read Property 'classList' of Undefined at Htmldivelement.".

I don’t know where the bug is, can you take a look? Thank you.

let jobCard = document.querySelectorAll('.job-card');
let jobResume = document.querySelectorAll('job-resume');
for(i = 0; i < jobCard.length;i++) {
    jobCard[i].addEventListener('click', function(){
        this.classList.add('job-card-active');
        jobResume[i].classList.add('d-block');
    });
}
  • your job-card is what exactly ? tagname ? id? than I saw in your code document.querySelectorAll('.job-card'); has the . job-card before or this is the search for a class?

  • 1

    On that line Let jobResume = document.querySelectorAll('job-resume'); not missing a point on the dial ('.job-resume')?

1 answer

2


In addition to the error quoted by @Augusto (missing . in the querySelctorAll) in the comments, you will have a problem with the variable i within your for.

When you click under one div.job-card the value of i (within the for) shall be equal to the number of Ivds having the class job-card. This is a classic problem of closure but I won’t get into this topic because for your case there is a simpler alternative, for example saving the i in a data- attribute.

I set an example by following the information you left, hopefully it will help:

let jobCard = document.querySelectorAll('.job-card');
let jobResume = document.querySelectorAll('.job-resume');

/*
for(i = 0; i < jobCard.length; i++) {
    jobCard[i].addEventListener('click', function() {
        this.classList.add('job-card-active');
        console.log(i); // Execute este trecho e veja o valor do "i" quando clicar em um div
        jobResume[i].classList.add('d-block');
    });
}
*/

for(i = 0; i < jobCard.length; i++) {
  jobCard[i].setAttribute('data-i', i);
  
  jobCard[i].addEventListener('click', function() {
    const idx = this.getAttribute('data-i');
    
    // Alterei o add pelo toggle
    this.classList.toggle('job-card-active');
    jobResume[idx].classList.toggle('d-block');
  });
}
.job-card-active {
    border: 1px solid #ff0000;
}

.d-block {
    display: block !important;
}

.job-resume {
    display: none;
}
<div class="job-card">Item 1</div>
<div class="job-resume">Reumo 1</div>
<div class="job-card">Item 2</div>
<div class="job-resume">Reumo 2</div>
<div class="job-card">Item 3</div>
<div class="job-resume">Reumo 3</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.