Search code examples
javascriptjqueryprototype

Translate insert new element from prototype de jquery


I am trying to translate the following prototype function :

function addCommentDump(message, type, info) {
    var commentDump = $('comment_dump');
    if (!commentDump) {
        var container = $('comment_dump_container');
        if (!container) {
            return;
        }
        container.insert(commentDump = new Element('div', {
            'id': 'comment_dump'
        }));
    }
    if (info) {
        message += ': ' + info;
    }
    commentDump.insert(new Element('span', {
        'class': type
    }).update(message));
}

to a jquery one. Here is the code:

function addCommentDump(message, type, info) {
    //alert("working.....");
    var $commentDump = $('#comment_dump');
    if (!$commentDump) {
        var $container = $('#comment_dump_container');
        if (!$container) {
            return;
        }
        $container.append($commentDump = new Element('div', {
            'id': 'comment_dump'
        }));
    }
    if (info) {
        message += ': ' + info;
    }
    $commentDump.append(new Element('span', {
        'class': type
    }).html(message));
}

I am getting an error: TypeError: Illegal constructor. Thanks in advance for your help.


Solution

  • Element is not the class in jQuery. You cannot call new Element. To create new element you can use $('<div />').

    Change this

    $container.append($commentDump = new Element('div', {
        'id': 'comment_dump'
    }));
    

    To

    $container.append($('<div />').attr({
        'id': 'comment_dump'
    }));
    

    AND

    $commentDump.append(new Element('span', {
        'class': type
    }).html(message));
    

    To

    $commentDump.append($('<span />').attr({
        'class': type
    }).html(message));