elementzero23
elementzero23

Reputation: 1429

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");
        }
    });
}

Upvotes: 1

Views: 2271

Answers (3)

madalinivascu
madalinivascu

Reputation: 32354

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/

Upvotes: 1

Mohit Tanwani
Mohit Tanwani

Reputation: 6628

Use .appendTo()

  • The .append() and .appendTo() methods perform the same task.
  • The major difference is in the syntax-specifically, in the placement of the content and target.
  • With .append(), the selector expression preceding the method is the container into which the content is inserted.
  • With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

Code Example

$('<div>Hello</div>', {
    "id": "pop-up" + id
}).appendTo($('#' + id).parent());

FYI,

Please make sure the element exists in the DOM and you're appending it in correct selector.

Hope this helps.

Upvotes: 2

Satpal
Satpal

Reputation: 133403

Create HTML using jQuery(html, attributes), You will be safe from quotes mess

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

Upvotes: 1

Related Questions