简体   繁体   中英

how insert element before anchor using javascript

function Insert_Icon() {
 var images = document.images;
 for (var i=0; i<images.length; i++){
    if (images[i].parentNode.tagName.toLowerCase()=='a') {
         var re = new RegExp("google\.com","ig");
        if (re.test(images[i].parentNode.href)){

            alert(images[i].parentNode.href);
        }
      /*  ---need insert this element before anchor----
       var currentElement = document.createElement("img");  
      currentElement.setAttribute("class", "icone"); 
      currentElement.setAttribute("src", "images/google.png"); */ 

    }
 }
}

all images with hyperlink for google show my png, try insertBefore but unsuccessfully

like this

<img class="icone" src="images/google.png"/><a href="http://google.com" target="_self"> <img class="cover_imagem" src="cover/2.jpg"</a>

I understand that this is not exactly the answer to your question, but you could try using css. This will not work in all browsers, however.

a[href^="http://google.com"]:before {
    content: url(http://g.etfv.co/http://www.google.com);
}

http://jsfiddle.net/kaleb/vbVck/

Using JavaScript to perform this operation in a loop will cause many redraws which can kill performance and perceived performance of your webpage. Ideally, you would use something like Modernizr to test if the user's browser supports these features and do the JS fallback only when necessary.

If you're saying the <img> needs to be removed from its parent <a> , and inserted before that <a> , then do this:

 // parent of <a>--------v    the <img>---------v   the <a>----------v
images[i].parentNode.parentNode.insertBefore( images[i], images[i].parentNode );

This invokes insertBefore on the parentNode of the <a> (that is the parentNode of the <img> ) and inserts the <img> before the <a> .

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