mazlix
mazlix

Reputation: 6293

jQuery append() adding at beginning

I want to turn something like <sup>1</sup> into <sup><a href="..." class="...">1</a></sup> I figured the easist way would be to prepend <a href....> and append </a> but the append is not coming after the content (1)...

I know I could do a second .each() and store the 1 as a variable and then do .html(), but I figure that's not best practice since it involves another loop.

Thanks!!

http://jsfiddle.net/pqzL4/

Upvotes: 1

Views: 2909

Answers (5)

David Ly
David Ly

Reputation: 31586

@Daff's answer should solve your problem. The reason it doesn't work is because as soon as you do:

$(this).prev(".article").find("sup").prepend("<a href=\"#references" + (i + 1) + "\" class=\"references\">");

It gets added immediately. Since an unclosed tag is invalid, the browser will "correct" it by closing the tag for you.

Then you try to add a close tag to the end, which is invalid without an open tag so the browser ignores it.

Upvotes: 7

John
John

Reputation: 171

I think what you're looking for is "wrapInner()". It takes the contents of one element and wraps it with an element you pass in. Something along the lines of

$('sup').wrapInner('<a href...></a>') 

Upvotes: 1

Daff
Daff

Reputation: 44215

I think you might want to look a jQuery wrapInner.

$('sup').wrapInner('<a href="#"></a>');

Which will wrap the text of any sup with a link.

Upvotes: 5

Mrchief
Mrchief

Reputation: 76218

Try this:

$(this).prev(".article").find("sup").append('<a>' + $(this).prev(".article").find("sup").text() + '</a>');

Upvotes: 0

SLaks
SLaks

Reputation: 887453

You cannot append or prepend HTML fragments; you can only work with complete tags.

You're looking for wrap.

Description: Wrap an HTML structure around each element in the set of matched elements.

Upvotes: 1

Related Questions