Search code examples
classmootoolswrapper

Mootools: wrap an element with an anchor while using a class selector


This is my first script, in any language, so yes, i am doing something wrong and it is probably something really really stupid.

I want to wrap the H3 below in between an anchor with Mootools.

First, i tested this with a ID instead of a class. This works. Apparently ('id') is good, ('.class') is bad. But for my specific usecase i need to select the element by its class.

HTML:

 <h3 class="class">test</h3>

Mootools code:

window.addEvent('domready', function () {

var test = document.getElements("h3.class");
var myAnchor = new Element('a', {
    href: 'http://www.someurl.com'
});

var myWrapper = myAnchor.wraps('.class');

});

I tried to create a var and grab the element here by its class. Yet i am not sure how to call this var inside wrap string.

var myWrapper = myAnchor.wraps(test);

Now i am stuck. I hope someone can help me out here, much appreciated.


Solution

  • Nearly.

    window.addEvent('domready', function () {
    
        var test = document.getElement("h3.class");
        var myAnchor = new Element('a', {
            href: 'http://www.someurl.com'
        });
    
        myAnchor.wraps(test);
    
    });
    

    http://jsfiddle.net/LmBVq/

    notice document.getElement (for a single element).

    the opposite of wrap is adopt. you could do myAchor.adopt(test); and then inject it somewhere else.