js增加给指定id下图片下增加链接

非常适用于医院网站站内文章这块

<div>1111<img src="https://www.baidu.com/img/gif_866f6aded1145a1188095fc88f4593d6.gif" />div>
<div id="a1">2222
    <img src="https://www.baidu.com/img/gif_866f6aded1145a1188095fc88f4593d6.gif" />
div>
<script>
function tihuanimg(id,href){
    //var allelem=document.all;
    var allelem=document.getElementById("a1").childNodes;
    for(i=0;ivar tagname;
        try{
            tagname=allelem[i].tagName.toLowerCase();
        }
        catch(e){
            continue;
        }
        if(tagname=='img'){
            if(allelem[i].parentNode.tagName.toLowerCase()=='a') continue;
            var newa=document.createElement("a");
            var thiselem=allelem[i];
            tihuanlink(thiselem,href);
        }
    }

}
function tihuanlink(thiselem,href){
    var newa=document.createElement("a");
    newa.href=href;
    newa.innerHTML=thiselem.outerHTML;
    var parent=thiselem.parentNode;
    parent.appendChild(newa)
    parent.removeChild(thiselem);
}
tihuanimg("a1","http://www.baidu.com");
script>

你可能感兴趣的:(Js)