Dynamically Insert Links Inside Span Tag Using Javascript

大憨熊 提交于 2019-12-04 09:23:55

This is how you can implement it:

function changespan() {
    var spans = document.querySelectorAll('span.image');
    for (var i = spans.length; i--; ) {
        var a = document.createElement('a');
        a.href = "http://domain.com";
        spans[i].appendChild(a).appendChild(a.previousSibling);
    }
}

http://jsfiddle.net/Tqv76/1/

Here, I translated it to JavaScript keeping your pseudo code as intact as possible

DEMO

window.onload=function() {
  var spans = document.getElementsByTagName("span"); // or the newer querySelectorAll
  for (var i=0;i<spans.length;i++) {
    if (spans[i].className=="image") {
      var link = document.createElement("a");
      link.href = "http://domain.com";
      link.setAttribute("rel","nofollow");
      link.className="someclass";
      link.innerHTML=spans[i].innerHTML;
      spans[i].replaceChild(link,spans[i].getElementsByTagName('img')[0]);
    }       
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!