Dynamically Insert Links Inside Span Tag Using Javascript

╄→尐↘猪︶ㄣ 提交于 2019-12-21 17:52:47

问题


I have this:

<span class="image"><img src="something.jpg"></span>

I want to transform it to that using javascript:

<span class="image"><a href="domain"><img src="something.jpg"></a></span>

It has to be done using javascript in order to hide the affiliate links.

I have tried this script but it seems not to work:

function changespan() {
find all <span> tags;
for each <span> with class="image"{
URL = "http://domain.com"
Create new link to URL;
insert link into <span>;
}       
}

The function is uploaded in file script.js and I load it in this fashion:

<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
window.onload = changespan;
</script>

EDIT: After this is solved, how could i parse my page to find links in this format: and then assign this value to variable URL. I need to be able to assign first path to URL_1 second to URL_2 and so on.


回答1:


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/




回答2:


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


来源:https://stackoverflow.com/questions/15340071/dynamically-insert-links-inside-span-tag-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!