Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery $.each gives me an object that does not have hasClass method

I'm trying to iterate over a collection of items with the class required. I think I must be using the $.each function incorrectly.

function required(address) {
    //object to hold elements not passing validation tests
    var pass = true;
    $('.required').each(function(index, elem){
        console.log(elem);
        //check if it has the class indicating it is an email
        if (elem.hasClass('re')) {
            var validEmail = validateEmail(address.email);
            if (!validEmail){
                $(this).addClass('nv'); 
            }

        }
      });
  }

I see that the element in the console is <input type=​"text" id=​"name_input" class=​"pr required">​

And then the error Uncaught TypeError: Object #<HTMLInputElement> has no method 'hasClass'

How can that object not have the hasClass method?

like image 651
1252748 Avatar asked Oct 23 '12 19:10

1252748


2 Answers

Your first hint should be that the object is an #<HTMLInputElement> and not a jQuery object. Use $(elem).hasClass('re');

like image 98
Barry Chapman Avatar answered Oct 13 '22 14:10

Barry Chapman


elem in your code is a DOM Element object, if you want to use jQuery methods you should create a jQuery object first:

if ($(elem).hasClass('re')) {
like image 38
undefined Avatar answered Oct 13 '22 14:10

undefined