Validation of javascript / jquery object?

Asked

Viewed 229 times

-4

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

I tried a few ways and I was unsuccessful:

//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 that worked:

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

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

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

2 answers

3


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

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

jQuery always returns an object. Be a selector, an array, etc. It always returns an object. When it uses

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

is checking to see if typeof {} !== "undefined" what always gives true.

2

You can use only (without >0):

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.