Validating the javascript / jquery object?

-4

I lost a little time with a javascript validation and I had the doubt in my head: I need to know if an element exists through id .

I tried some ways and I did not succeed:

//tentativa 1
$('#idDiv').val() != undefined

//tentativa 2
typeof($('#idDiv').val()) != 'undefined'

//tentativa 3
var varIdDiv = $('#idDiv').attr("value");
if (varIdDiv) { /*código maroto*/ }

Finally I found a way to validate what worked:

if ($('#idDiv').length > 0) { /*código maroto*/ }

I understand that in languages like C # , the validation looks more like the shapes that did not work (checking if the object exists / not null).

My question is what would be the most effective way to validate if an object exists via javascript / jquery ?

    
asked by anonymous 18.08.2017 / 18:25

2 answers

3

What you want to use is the .length property that indicates the number of elements in the jQuery object.

if ($("#idDiv) { console.log("existe"); }

jQuery always returns an object. Be a selector, array, etc. It always returns an object. When you use

if (typeof($("#idDiv")) !== "undefined") { console.log("existe");  }

You are checking whether typeof {} !== "undefined" is always true.

    
18.08.2017 / 19:05
2

You can only use (without >0 ):

if ($('#idDiv').length) { /*código maroto*/ }

Because if the object exists, it will return >0 or true , otherwise, 0 or false .

    
18.08.2017 / 19:00