javascript if element exists code example

Example 1: js element exists

var element = document.getElementById("test");
    //If it isn't "undefined" and it isn't "null", then it exists.
if(typeof(element) != 'undefined' && element != null){
    alert('Element exists');
} else{
	alert('Element does not exist');
}

Example 2: check if the element exists in javascript

<div id="test">Example DIV element.</div>
 
<script>
    //Attempt to get the element using document.getElementById
    var element = document.getElementById("test");
 
    //If it isn't "undefined" and it isn't "null", then it exists.
    if(typeof(element) != 'undefined' && element != null){
        alert('Element exists!');
    } else{
        alert('Element does not exist!');
    }
</script>

Example 3: js check if dom element exists

var myElement = document.getElementById("myElementID");

if(!myElement){
    //#myElementID element DOES NOT exist
}

if(myElement){
    //#myElementID element DOES exists
}

Example 4: java check if element exists in array

package com.mkyong.core;

import java.util.Arrays;
import java.util.List;

public class StringArrayExample1 {

    public static void main(String[] args) {

        String[] alphabet = new String[]{"A", "B", "C"};

        // Convert String Array to List
        List<String> list = Arrays.asList(alphabet);
        
        if(list.contains("A")){
            System.out.println("Hello A");
        }

    }

}
Copy

Example 5: check if the element exists in javascript

var myEle = document.getElementById("myElement");
    if(myEle){
        var myEleValue= myEle.value;
    }

Tags:

Php Example