ECMAScript
ECMAScript

Reputation: 4649

How to create a new anchor tag around an existing element

<span class="classname">
<img src="" width="70" height="70">
</span>

I'm trying to add an anchor tag with a URL around the tags. I'm not sure how to do it and I've been stumped for hours..

Upvotes: 2

Views: 2957

Answers (2)

painotpi
painotpi

Reputation: 6996

Try the jQuery .wrap() method,

$("span.avatar").wrap("<a></a>");

Pure JS:

var target = document.getElementsByClassName("avatar")[0];
var wrap = document.createElement("a");

target.parentNode.replaceChild(wrap, target); 
wrap.appendChild(target);

Upvotes: 5

Arun P Johny
Arun P Johny

Reputation: 388316

Try

var el = document.getElementsByClassName('avatar')[0];
var anchor = document.createElement('a');
el.parentNode.insertBefore(anchor, el);
anchor.appendChild(el)

Demo: Fiddle

Upvotes: 2

Related Questions