简体   繁体   中英

JS check if getElementById exists

This is part of my class homework. It is a small web application. The code part below is a function for a select button (checkbox). The code is working fine.

My issue is I get this error on console:

Uncaught TypeError: Cannot set property 'checked' of null
at selectGirls (indexj.js:163)
at HTMLAnchorElement.onclick (index.html:137)

I know I get this error because, I haven't these elements on every page. To clarify that, I mean page 1 has two checkboxes, but page 2 has 5 checkboxes, like that.

I want to use this same JS file for all pages. My question is how can I avoid these console errors best way possible? I do not want to make them hide from console as a solution. I really appreciate your input.

 function selectAllStudents() { unselectAllStudents(); let boxes = $(".scores").toArray(); document.getElementById('check_Terrilyn').checked = true; document.getElementById('check_Vinnie').checked = true; document.getElementById('check_Boren').checked = true; document.getElementById('check_Tempie').checked = true; document.getElementById('check_Mapes').checked = true; document.getElementById('check_Fletcher').checked = true; document.getElementById('check_Bovee').checked = true; document.getElementById('check_Figgs').checked = true; }

The simplest is to check if they are there

if (document.getElementById('check_Terrilyn'))
  document.getElementById('check_Terrilyn').checked = true;

Edit

A more modern approach, and given that there are an unknown amount of checkboxes, could be to use querySelectorAll .

It will return an array of elements, and eg, and as your code suggest, all the checkeboxes's id starts with check_ , you can use it like this with an attribute selector :

 var els = document.querySelectorAll('[id^="check_"]'); els.forEach(function (el) { el.checked = true; });
 <input id="check_0" type="checkbox" value="0"> <input id="check_1" type="checkbox" value="1"> <input id="check_2" type="checkbox" value="2"> <input id="check_3" type="checkbox" value="3">

Approach with id and if

if (document.getElementById('check_Terrilyn')){
    document.getElementById('check_Terrilyn').checked = true;
}

Approach with classes

//ES6
Array.from(document.getElementsByClassName('commonclass')).forEach(e => {
    e.checked = true;
});

You can do somewhat like this:

let elm = document.getElementById('check_Terrilyn');

elem && elem.checked = true;

I use to do

if(document.getElementById('check_Terrilyn')!="null")
    document.getElementById('check_Terrilyn').checked=true;

I see you're already using jQuery. Why not use it fully, and stop using getElementById ?

Just do $( ... ).prop('checked',true) . jQuery will handle the case where the element is not found.

function selectAllStudents() {
    unselectAllStudents();
    let boxes = $(".scores").toArray();
    $('#check_Terrilyn, #check_Vinnie, #check_Boren, #check_Tempie, #check_Mapes, #check_Fletcher, #check_Bovee, #check_Figgs').prop('checked',true);
}

If you're setting them all to a checked state, then select them by class and loop through them all. That way it won't matter if none are found.

You also appear to be using jQuery, so the code can then be simplified to just:

function selectAllStudents() {
  unselectAllStudents();
  let boxes = $(".scores").toArray();
  $('.checkbox').prop('checked', true);
}

Since you have tagged jquery, use prop

function selectAllStudents() {
    unselectAllStudents();
    let boxes = $(".scores").toArray();
    $('#check_Terrilyn').prop( "checked", true );
    //for the rest of them
}

Or create an array of ids which you can iterate and check if they exists before setting their checked property

var array = ['check_Terrilyn', 'check_Vinnie']; //add more ids as required
array.forEach( s => $("#"+s).prop( "checked", true ) );

Or with plain js

var array = ['check_Terrilyn', 'check_Vinnie']; //add more ids as required
var fnGetEl = (id) => document.getElemetById(id);
array.forEach( s => {
  var el = fnGetEl(s);
  if(el)
  {
    el.checked = true;
  }
});
if(document.getElementById("id_selector2teller")){
alert("id_selector2teller exists");
}else{
alert("id_selector2teller not available");
}

This works if you want to check if element exists and at the same time assign it to a variable (and make it 'false' if the element doesn't exist):

var check_Terrilyn = document.getElementById('check_Terrilyn') ?
                     document.getElementById('check_Terrilyn').checked : false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM