0

So far, I've got this code:

$("<div/>", {
    "id": "myId",
    "class": "myClass",
    "html": "Hello world!"
}).appendTo("#myContainer");

This appends

<div id="myId" class="myClass">Hello world!</div>

to #myContainer, as one would expect.

But instead of appending, I would like to have it replace the contents. I'm imagining something like this:

$("#myContainer").html("<div/>", {
    "id": "myId",
    "class": "myClass",
    "html": "Hello world!"
});

1 Answer 1

1

Actually, this is really easy to do, you just have to wrap the dynamic HTML in $() (or jquery(), if you prefer) again:

$("#myContainer").html($("<div/>", {
    "id": "myId",
    "class": "myClass",
    "html": "Hello world!"
}));

Even though this works perfectly fine, I'm wondering if there's a more elegant/performant way of doing this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.