Search code examples
mootools

MooTools inject an element at nth position


I am trying to inject an element at nth postion. For example, consider that I am having an div and div contains 4 p tag, now I want to inject one more p tag at 2nd position. Is it possible?


Solution

  • Yes, its possible. You can use the Element.inject API and do like this:

    yourNewElement.inject(theReferenceElement, 'after');

    That way you specify the the element should be added after the reference element you had.

    Example:

    var p = new Element('p', {
        html: 'Hello!'
    });
    var second = $$('div p')[2];
    p.inject(second, 'after');
    <script src="https://ajax.googleapis.com/ajax/libs/mootools/1.6.0/mootools.min.js"></script>
    
    <div>
        <p>1</p>
        <p>2</p>
        <p>3</p>
        <p>4</p>
        <p>5</p>
    </div>

    jsFiddle: https://jsfiddle.net/9y8xch4k/