Ryan Palmer
Ryan Palmer

Reputation: 443

jQuery: Create an element inside another created element

In the following string, I'm trying to add an additional span around the post.caption but keep it inside the <span class="overlay" />. I've tried prepend and wrap before and after the .html, but can't get it or anything to do it correctly.

$('<span class="overlay" />').html(post.caption).appendTo(entry);

Result would look like <span class="overlay"><span>Caption content</span></span>

Here's the full snippet if that helps:

entry = $('<a />').attr('href', post.permalinkFull)
        $('<img />').attr('src', post.image).appendTo(entry)
        $('<span class="overlay" />').html(post.caption).appendTo(entry);

Any help would be hugely appreciated!

Upvotes: 0

Views: 62

Answers (2)

Jai
Jai

Reputation: 74738

You can try this with wrapInner:

$('<span class="overlay" />').html(post.caption)
                             .wrapInner('<span />').appendTo(entry);

Upvotes: 3

mitai
mitai

Reputation: 314

if post.caption is a string, then as I understand it you also want to create the span around it:

$('<span>').html(post.caption).appendTo(entry).wrap('<span class="overlay" />');

Upvotes: 3

Related Questions