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 ?
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>
1 answer