$ is not defined error in mootools

201 views Asked by At
(function () {
    //alert("hi");
    var divtag = $('maindiv').get('tag');
    //var divtag=document.getElementById("maindiv");
    console.log(divtag);

    var username = new Element("input", {
        "type": "text",
        "name": "username",
        "id": "name",
        "placeholder": "Enter username here"
    });
    divtag.inject(username);
})();

here is the code of my js file.Please let me know where i m making mistake.

1

There are 1 answers

6
rsp On

If this works:

(function () {

    // >>> EXPLICITLY SET $ TO document.id:
    var $ = document.id;

    // >>> THE REST OF YOUR CODE:

    //alert("hi");
    var divtag = $('maindiv').get('tag');
    //var divtag=document.getElementById("maindiv");
    console.log(divtag);

    var username = new Element("input", {
        "type": "text",
        "name": "username",
        "id": "name",
        "placeholder": "Enter username here"
    });
    divtag.inject(username);
})();

then the $ alias for document.id is not defined, or is defined by some other library than MooTools (maybe jQuery is also included on the page?).

(Redefining the $ as var $ = document.id; inside your own function is safe even if $ is already defined to be something else and used outside of your function - the outside $ will not be changed here.)

Another thing is this:

var divtag = $('maindiv').get('tag');

which should probably be just:

var divtag = $('maindiv');

I assume that you have the MooTools library loaded on the page - if you don't then of course nothing will work.

Posting a link to a code example on JSFiddle, JS Bin or CodePen would make it much easier to diagnose your problem.