2

I have written some vanilla JS in order to hide/display some divs, depending on the value of one of the fields in them.

My problem is that, while hiding them appropriately is working by default, trying to make them appear again, I am having issues as using getElementById is returning nulls.

I've googled and found numerous examples where similar code has worked and I cannot figure out why mine isn't actually working.

The JS I've written is below:

var hidden = false
document.addEventListener("keypress", function(event) {
  if (event.key == '`') {
    if (hidden == false) {
      resultEntries = document.getElementsByClassName('result-row');
      for (i = 0; i < resultEntries.length + 1; i++) {
        var x = document.getElementById('root_cause_' + i)
        if (x != null) {
          var value = x.options[x.selectedIndex].value;
          console.log('value' + value)
          if (value == '') {
            row = document.getElementById('line_' + i)
            row.style.display = 'none';
          }

        }
      }
      hidden = true
    } else {
      resultEntries = document.getElementsByClassName('result-row');
      for (i = 0; i < resultEntries.length + 1; i++) {
        row = document.getElementById('line_' + i) // This is what is returning null
        console.log(row)
        row.style.display = 'block';
      }
      hidden = false
    }
  }
});

1
  • 3
    Please add relevant HTML and CSS to the snippet I made you Commented Sep 13, 2022 at 14:13

2 Answers 2

2

You overshoot your elements with the + 1 in the for loops

If you need this 1 based (not recommended) it is

for (let i = 1; i <= resultEntries.length; i++) 

Also I think you can simplify this. Here is my guess without seeing the HTML

const resultEntries = document.querySelectorAll('.result-row');
document.addEventListener("keypress", function(event) {
  if (event.key !== '`') return;
  resultEntries.forEach((res, i) => {
    let x = document.getElementById('root_cause_' + i)
    if (x) {
      let value = x.value;
      console.log('value' + value)
      document.getElementById('line_' + i).hidden = value === '';
    }
  })
});
Sign up to request clarification or add additional context in comments.

1 Comment

It turns out it was something different all-together. I have answered to save people from spending time. Your code was really useful to understand what was wrong and further simplify my code so I am up voting this, thank you.
0

Answering to save people from spending more time on this:

The issue was that my loop was starting from 0 while the elements were starting from line_1, meaning I was later on trying to alter the style of a null element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.