Search code examples
jqueryhtmlappendstring-concatenation

jQuery append() not working for concatenated String


(Full code below)

This

$('#' + id).parent().append('<div id="pop-up">hello</div>');

does work. But this

$('#' + id).parent().append('<div id="pop-up-' + id + '">hello</div>');

doesn't.

The fact that the first version works lets me assume that the problem is not the id variable...

So the full code is

function clickOnElement(id) {
    var obj = {};
    obj.clicked = String(id);
    var jsonData = JSON.stringify(obj);
    $.ajax({
        type: 'POST',
        url: '../db/RequestHandler.ashx',
        data: jsonData,
        contentType: 'application/json; charset-utf-8',
        success: function (response) {
            // Add the div for the dialog-box
            $('<div>Hello</div>', {
                "id": "pop-up" + id
            }).appendTo($('#' + id).parent());
        },
        error: function () {
            console.log("request error");
        }
    });
}

Solution

  • Try the following

    var parent = $('#' + id).parent();
    var el = $('<div>', {id: "pop-up"+id,text:"hello"});
     el.appendTo(parent);
    

    the proper way to add text to a created object is to use the text property:

    demo:https://jsfiddle.net/gx6mrqr7/