How to check if element exists in DOM

Javascript Post
Follow us

Flawlessness is one of the skills that every good developer follows. Writing the code should not affect other modules. As a web developer, when you work with HTML elements and DOM, it’s good practice to check whether the corresponding element exists before performing any operations on it.

You can do this by Javascript or jQuery

		<p id="pag"> Welcome to CodesVila </p>
// Using Pure Javascript 
var element =  document.getElementById('pag');
if (typeof(element) != 'undefined' && element != null){
  // Exists.

// Using jQuery Library 
if ($('#pag').length > 0){
  // Exists.

jQuery makes our job easy.

Leave a Comment

Your email address will not be published. Required fields are marked *