简体   繁体   中英

How to edit external links with javascript

i want to edit all external links that inside class example

<div class='main'>
<a href='http://test1.com'>link1</a>
<a href='http://test2.com'>link1</a>
<a href='http://test3.com'>link1</a>
</div>

i want to edit all link that inside main class and add before the link another link like this

<div class='main'>
<a href='http://example.com/search=http://test1.com'>link1</a>
<a href='http://example.com/search=http://test2.com'>link2</a>
<a href='http://example.com/search=http://test3.com'>link3</a>
</div>

sorry for my english

if each link has it's own id like

<a id="link1" href='http://test1.com'>link1</a>

then try this

var currentAddress = document.getElementByID("link1").attr("href")

document.getElementByID("link1").attr("href", "http://example.com/search=" + currentAddress)

you can get all the links using document.querySelectorAll('.main a') , iterate over them and then use replace() on each link's href to add the missing part in href.

 var links = document.querySelectorAll('.main a'); for(var i=0; i<links.length; i++){ links[i].href = links[i].href.replace("http://", "http://example.com/search=http://"); } 
 <div class='main'> <a href='http://test1.com'>link1</a> <a href='http://test2.com'>link1</a> <a href='http://test3.com'>link1</a> </div> 

You should be able to get a collection of the "a" tags using javascript (or jQuery if you have access to that) using an x-path specification. Once you have the collection you should be able to iterate through it and set the new value.

Here's some info on x-path.
https://www.w3schools.com/xml/xpath_examples.asp

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