How to check for an item?

I use a method .lengthin a conditional expression that checks the page for an object loaded from the outside (I cannot style it with jQuery until it exists):

function hackyFunction() {
  if($('#someObject').length<1)
  { setTimeout(hackyFunction,50) }
  else
  { $('#someObject').someMethod() }}

Is the lengthbest way to do this?

+3
source share
5 answers

Yes you should use .length. You cannot use if ($('#someObject')) ...it because jQuery selectors return a jQuery object and any object is believable in JavaScript.

+4
source

If you are just looking for a specific item, you can simply use document.getElementById

function hackyFunction() {
    if (document.getElementById("someObject")) {
         // Exist
    } else {
         // Doesn't exist
    }
}
+8
source

, , :

if($('#someObject')[0])
+3

, .length .

+2

jQuery .

if (!$('#someObject').length) {
    console.log('someObject not present');
}

Of course, with vanilla JavaScript you can just check with document.getElementById(if you get elements by id)

if (document.getElementById('someObject')) {
    console.log('someObject exists');
}
0
source

Source: https://habr.com/ru/post/1768849/


All Articles