user1301744
user1301744

Reputation: 113

Defining Javascript function with prototype property

What's wrong with this piece of code?

(function (){
    'use strict';

    // add hasClass function
   String.prototype.hasClass = function (className) {
       return this.className.search('(\\s|^)' + className + '(\\s|$)') != -1 ? true : false;
   };

   console.log(document.getElementById('link').hasClass('test'));    
})();

I'd expect it to return true or false, but all I get is

TypeError: document.getElementById("link").hasClass is not a function**

UPD: Thanks guys. Now i get it. I should set method to Object or Element (What is more right?) not String!

Upvotes: 1

Views: 191

Answers (3)

danp
danp

Reputation: 15241

The way to do this is to write a function that receives a DOM element, as the String object has nothing to do with it ;)

A simple example:

function hasClass(element, classcheck){
  return element.className.indexOf(classcheck) !== -1;
}

So your code would look like:

(function (){
    'use strict';

    // add hasClass function
    function hasClass(element, classcheck){
      return element && element.className && element.className.indexOf(classcheck) !== -1;
    }

   console.log(hasClass(document.body,'test'));
})();

Obviously, you should be checking that the first argument is actually a DOM element too (quite a lot of different ways to achieve that), but this is the right way to go about it.

Upvotes: 1

tinyd
tinyd

Reputation: 952

document.getElementById('link') doesn't return a String, it returns a DOM element. You could try this instead:-

 Element.prototype.hasClass = function (className) {
       return this.className.search('(\\s|^)' + className + '(\\s|$)') != -1 ? true : false;
   };

   console.log(document.getElementById('link').hasClass('test'));   

Upvotes: 4

Vala
Vala

Reputation: 5674

As far as I know, hasClass is not a method of Element, you're likely thinking of the jQuery method, as such you would have to use jQuery and select the element using a jQuery selector. Other frameworks may also have such methods, I believe YUI does as well.

Upvotes: 1

Related Questions