Matt Coady
Matt Coady

Reputation: 3856

jQuery append to adjacent element

Here's the structure.

<div>
  <a>Blah</a>
  <span>5</span>
</div>
<div>
  <a>Blah</a>
  <span>6</span>
</div>

and here's what I want

<div>
  <a>Blah<span>5</span></a>
</div>
<div>
  <a>Blah<span>6</span></a>
</div>

here's what I tried

$("div span").appendTo("a", this);

but I ended up with both spans landing in both a elements.

Upvotes: 0

Views: 94

Answers (3)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

Not quite as elegant as koala's answer but this is what I came up with:

$('div span').each(function() {
    $(this).parent().find('a').append($(this).detach());
});

Working Demo (jsFiddle)

Upvotes: 2

Alexandru Diacov
Alexandru Diacov

Reputation: 1191

var span = "<span></span>";
$("div a").append(span);

or try this

var span = "<span></span>";
$("div a").html(span);

FIDDLE

Upvotes: -2

omma2289
omma2289

Reputation: 54619

$("div span").each(function () {
    $(this).appendTo($(this).prev('a'));
});

Upvotes: 3

Related Questions