Ashonko
Ashonko

Reputation: 623

Resolve the error: Cannot read property 'style' of null" with a better approach?

I have a common js file for 2 different pages. In Page 1, I just want to show the text2 field when the LName input has any value. Otherwise, I want it to be hidden. So I created an if condition to see whether there is any value for the LName input and if there is no value, I kept the display: none;.

In Page 2, I don't need the div for id="text2", so dropped it. As a result, whenever I give an input, it returns an error as there is no div with id="text2".

I need a single js file, at the same time, I need to show the text2 div in Page 1 but I don't want to keep the <div id="text2" class="display: none;"></div> in the Page 2 as I don't need it there. How can I solve this problem? Is there any better approach I could take?

This is the working Page 1 in jsfiddle.

And this is the Page 2 in the snippet, that returns an error:

$(document).ready(function() {
  $(document).on("keyup change", "#FName, #LName", function() {
    var FName = $('#FName').val();
    var LName = $('#LName').val();

    var listP = document.getElementById('list');
    if ($('#FName').val() == "") {
      listP.style.display = 'none';
    } else {
      listP.style.display = 'block';
    }

    var text2P = document.getElementById('text2');
    if ($('#LName').val() == "") {
      text2P.style.display = 'none';
    } else {
      text2P.style.display = 'block';
    }

    $('#text1').html('<li>This is text 1</li>');
    $('#text2').html('<li>This is text 2</li>');
    $('#text3').html('<li>This is text 3</li>');

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
FName: <input name="FName" id="FName"><br> LName: <input name="LName" id="LName"><br>
<div id="list">
  <div id="text1"></div>
  <div id="text3"></div>
</div>

Upvotes: 0

Views: 56

Answers (1)

raul.vila
raul.vila

Reputation: 1984

Check if text2P is not falsy:

var text2P = document.getElementById('text2');
if (text2P) {
    if ($('#LName').val() == "") {
        text2P.style.display = 'none';
    } else {
        text2P.style.display = 'block';
    }
}

Doc

MDN web docs: Falsy

Upvotes: 1

Related Questions