Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 790
Berglund Avatar asked Nov 28 '22 13:11

Berglund


2 Answers

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 e.g., 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">
like image 73
Asons Avatar answered Dec 05 '22 13:12

Asons


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;
});
like image 42
Cristian S. Avatar answered Dec 05 '22 13:12

Cristian S.