Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - check if variable is dom element

Is there any way to check if given variable is not-empty jQuery object or native DOM element?

so it would be like

isDomElem( $("#some-existing-element") ); //returns true
isDomElem( $("#some-existing-element")[0] ); //returns true
isDomElem( $("#non-existing-element")[0] ); //returns false
isDomElem( "#some-existing-element" ); //returns false
isDomElem( [0,1,2] ); //returns false
//etc... 
like image 663
Adam Pietrasiak Avatar asked Feb 02 '15 21:02

Adam Pietrasiak


People also ask

How do I know if a element is DOM?

To check if an element does not exist in the DOM: Use the getElementById or querySelector methods to select the element. Check if the stored value is equal to null . If the value is equal to null , the element does not exist in the DOM.

What is $El in jQuery?

The code means that $. el namespace will have the function laconic() and this function create elements using document. createElement and append to the body.

How do I check if a div exists?

$(document). ready(function() { if ($('#DivID'). length){ alert('Found with Length'); } if ($('#DivID'). length > 0 ) { alert('Found with Length bigger then Zero'); } if ($('#DivID') !=

How to check if an element is present in Dom with jQuery?

To check if an element is present in DOM with jQuery, you can use the selectors. They return one or more matching elements within a document. Then check the .length property or call the .size () method to get the size of the jQuery object array returned. 2. Using $ (selector) [0]

How to check whether a JavaScript object is a DOM object?

Approach: In order to check whether a JavaScript object is a DOM object, we need to check whether the given JS object is of Element type Object. In order to check this, we will use instanceof operator.

How do I select a DOM element from a variable?

If you have a variable containing a DOM element, and want to select elements related to that DOM element, simply wrap it in a jQuery object. var myDomElement = document.getElementById ( "foo" ); // A plain DOM element. $ ( myDomElement ).find ( "a" ); // Finds all anchors inside the DOM element.

What are the two arguments of the index function in jQuery?

It accepts two arguments, index, which is the element's index in the jQuery collection, and element, which is the DOM element. Within the function, this refers to the current DOM element. An existing jQuery object to match the current set of elements against. One or more elements to match the current set of elements against.


2 Answers

You can use instanceof to check if the object passed in is an instanceof jQuery or an instanceof HTMLElement. If it is return true;. Otherwise, return false.

function isDomElem(obj) {
      if(obj instanceof HTMLCollection && obj.length) {
          for(var a = 0, len = obj.length; a < len; a++) {
              if(!checkInstance(obj[a])) {
                  console.log(a);
                  return false;   
              }
          }     
          return true;                
      } else {
          return checkInstance(obj);  
      }

      function checkInstance(elem) {
          if((elem instanceof jQuery && elem.length) || elem instanceof HTMLElement) {
              return true;  
          }
          return false;        
      }
}

Optionally, instead of returning true or false, you could do some other action. You could also split each option out and do a separate action depending on which one the object is an instance of jQuery or HTMLElement. You have lots of choices to choose from.

$(function () {
  var temp1 = $('div'),
      temp2 = $('div')[0],
      temp3 = "foo",
      temp4 = ['bar'],
      temp5 = $('span'),
      temp6 = document.getElementsByClassName("test");
  
  alert(isDomElem(temp1));
  alert(isDomElem(temp2));
  alert(isDomElem(temp3));
  alert(isDomElem(temp4));
  alert(isDomElem(temp5));
  alert(isDomElem(temp6));
  
  function isDomElem(obj) {
    
      if(obj instanceof HTMLCollection && obj.length) {
        
        for(var a = 0, len = obj.length; a < len; a++) {
            if(!checkInstance(obj[a])) {
                return false;   
            }
        }
               
        return true;
               
      } else {
          return checkInstance(obj);  
      }
        
      function checkInstance(elem) {
          if((elem instanceof jQuery && elem.length) || elem instanceof HTMLElement) {
              return true;  
          }
          return false;        
      }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<p class="test"></p>
<p class="test"></p>

EDIT:

@RickHitchcock made a very valid point regarding the function returning an instance of jQuery with no matched elements. For this reason, I've updated the function to take into account not only if the object is an instanceof jQuery but also if the object has a length, indicating whether a DOM element was found.

EDIT:

An additional edit was made per @AdamPietrasiak's comment below regarding instances of HTMLCollections returning false. In this case, if the obj passed in is an instance of HTMLCollection, each element is passed to the internal checkInstance function. Any element which is not a DOM node triggers the function to throw an overall false regardless of whether there was an element in the list (i.e. for instances of HTMLCollection the function treats it as an all or nothing).

like image 135
War10ck Avatar answered Oct 28 '22 08:10

War10ck


I think this covers all cases:

console.clear();
function isDomElem(el) {
  return el instanceof HTMLElement || 
         el[0] instanceof HTMLElement ?
         true : false;
}

console.log(isDomElem($("#some-existing-element"))); //returns true
console.log(isDomElem($("#some-existing-element")[0])); //returns true
console.log(isDomElem($("#non-existing-element"))); //returns false
console.log(isDomElem("#some-existing-element")); //returns false
console.log(isDomElem([0,1,2])); //returns false
console.log(isDomElem(document.getElementsByClassName("a"))); //returns true
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="some-existing-element" class="a"></div>
<div class="a"></div>
like image 38
Rick Hitchcock Avatar answered Oct 28 '22 07:10

Rick Hitchcock