In my JavaScript I want to check whether the element with specific id is exist or not, I tried it with 2 ways
1).
var myEle = document.getElementByI
You need to specify which object you're calling getElementById from. In this case you can use document. You also can't just call .value on any element directly. For example if the element is textbox .value will return the value, but if it's a div it will not have a value.
You also have a wrong condition, you're checking
if (myEle == null)
which you should change to
if (myEle != null)
var myEle = document.getElementById("myElement");
if(myEle != null) {
var myEleValue= myEle.value;
}
You can simply use if(yourElement)
var a = document.getElementById("elemA");
var b = document.getElementById("elemB");
if(a)
console.log("elemA exists");
else
console.log("elemA does not exist");
if(b)
console.log("elemB exists");
else
console.log("elemB does not exist");
<div id="elemA"></div>
getElementById
Return Value: An Element Object, representing an element with the specified ID. Returns null if no elements with the specified ID exists see: https://www.w3schools.com/jsref/met_document_getelementbyid.asp
Truthy vs Falsy
In JavaScript, a truthy value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN). see: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
When the dom element is not found in the document
it will return null
. null is a Falsy and can be used as boolean expression
in the if statement.
var myElement = document.getElementById("myElement");
if(myElement){
// Element exists
}
var myEle = document.getElementById("myElement");
if(myEle){
var myEleValue= myEle.value;
}
the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value
document.getElementById('yourId')
is the correct way.
the document refers the HTML document that is loaded in the DOM.
and it searches the id using the function getElementById() which takes a parameter of the id of an element
Solution will be :
var elem = (document.getElementById('myElement'))? document.getElementById('myElement').value : '';
/* this will assign a value or give you and empty string */
Use typeof for elements checks.
if(typeof(element) === 'undefined')
{
// then field does not exist
}