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.getElementById("myElement");
if(myEle == null){
var myEleValue= document.getElementById("myElement").value;
}
2).
if(getElementById("myElement")){
var myEleValue= document.getElementById("myElement").value;
}
but it gives same error as below -
Object expected
getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” 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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With