Check if document getElementById or getElementsByName exists

How can I check if input field or other element exists by using document.getElementById or document.getElementsByName, before trying to get values ?
0
give a positive ratinggive a negative rating
13 Dec 2022 at 05:41 PM
Hi,

To check if input field, textarea or other HTML element exists using a Javascript, you can use multiple ways how to do so:

<script>

function checkID() {
if(document.getElementById('a')) { alert('Element exists'); }
else{ alert('Element does not exist'); }
}

function checkName() {
if(document.getElementsByName('b')) { alert('Element exists'); }
else{ alert('Element does not exist'); }
}

</script>

<input type='text' id='a' value='content' />
<input type='text' name='b' value='content' />
<a href='javascript: void(0);' onClick='javascript: checkID();'>Check ID</a>
<a href='javascript: void(0);' onClick='javascript: checkName();'>Check Name</a>

Alternatively, you can use:

<script>

function checkID() {
if(document.getElementById('a')!==null) { alert('Element exists'); }
else{ alert('Element does not exist'); }
}

function checkName() {
if(document.getElementsByName('b')!==null) { alert('Element exists'); }
else{ alert('Element does not exist'); }
}

</script>

0
give a positive ratinggive a negative rating
14 Dec 2022 at 05:55 PM
Tim
Share on FacebookShare on TwitterShare on LinkedInSend email
x
x
2024 AnswerTabsTermsContact us