Search code examples
javascriptgetelementbyid

getElementById and skip if null


When it returns null it does not run the next getElementById. What is the best way to structure this? There will be 12 possible getElementById but a page may only have 2 - 4

document.getElementById("routeTwoName").textContent = "Tim";
document.getElementById("routeThreeName").textContent = "David";
document.getElementById("routeFourName").textContent = "Ricky";
document.getElementById("routeTenName").textContent = "Ric";
<div class="panel-body">
  <h4><span id="routeTwoName">Name</span></h4>
</div>

<div class="panel-body">
  <h4><span id="routeTenName">Name</span></h4>
</div>


Solution

  • In general, when you have this sort of repeated logic, you encapsulate the logic in a function:

    function setText(id, text) {
        var element = document.getElementById(id);
        if (element) {
            element.textContent = text;
        }
        return element;
    }
    

    then you can do this:

    setText("routeTwoName", "Tim");
    setText("routeThreeName", "David");
    setText("routeFourName", "Ricky");
    setText("routeTenName", "Ric");
    

    Here's an updated version of the snippet from the question:

    function setText(id, text) {
        var element = document.getElementById(id);
        if (element) {
            element.textContent = text;
        }
        return element;
    }
    setText("routeTwoName", "Tim");
    setText("routeThreeName", "David");
    setText("routeFourName", "Ricky");
    setText("routeTenName", "Ric");
    <div class="panel-body">
      <h4><span id="routeTwoName">Name</span></h4>
    </div>
    
    <div class="panel-body">
      <h4><span id="routeTenName">Name</span></h4>
    </div>

    Another option is to give yourself a bunch of set-based DOM manipulation functions (like jQuery's API, but without using jQuery [unless you want to, of course; it's already written and tested]) rather than element-based ones like the DOM's. My answer here has an example of starting down that path.