最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create a new anchor tag around an existing element - Stack Overflow

programmeradmin2浏览0评论
<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..

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

Share Improve this question edited Jun 18, 2013 at 6:33 ECMAScript asked Jun 18, 2013 at 6:08 ECMAScriptECMAScript 4,6494 gold badges23 silver badges29 bronze badges 5
  • 2 around span or img? – Sergio Commented Jun 18, 2013 at 6:09
  • 2 can't you add it in the markup directly? what problem are you facing? what should be the expected behavior? – painotpi Commented Jun 18, 2013 at 6:10
  • you have to explain in details. What exactly you want to see in output – Rakesh Shetty Commented Jun 18, 2013 at 6:12
  • Around the span tag. I need to do it in javascript. – ECMAScript Commented Jun 18, 2013 at 6:13
  • 1 I think what you are looking for is just this. – ibi0tux Commented Jun 18, 2013 at 6:15
Add a ment  | 

2 Answers 2

Reset to default 5

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

发布评论

评论列表(0)

  1. 暂无评论