简体   繁体   中英

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..

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);

Try

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

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM