I have a use case, where i have to select all <a>
, containing string in url like "/web/local" and remove "/web/local" from all href of all these links.
Note: i can't use jQuery. I can use either pure js or YUI.
Thanks in advance.
See comments inline:
let phrase = "/web/local"; // Get all the links that contain the desired phrase into an Array let links = Array.prototype.slice.call(document.querySelectorAll("a[href*='" + phrase +"']")); // Loop over results links.forEach(function(link){ // Remove the phrase from the href link.href = link.href.replace(phrase, ""); }); // Just for testing: console.log(document.querySelectorAll("a"));
<a href="http://www.something.com/web/local">Some Link</a> <a href="http://www.something.com/web/local">Some Link</a> <a href="http://www.something.com/web/local">Some Link</a> <a href="http://www.something.com/web/local">Some Link</a> <a href="http://www.something.com/web/local">Some Link</a>
In order to get /set correctly the href attribute you need to use getAttribute / setAttribute :
document.querySelectorAll('a[href*="/web/local"').forEach(function(ele) { ele.setAttribute('href', ele.getAttribute('href').replace('/web/local', '')); console.log(ele.outerHTML); });
<a href="/web/local"></a> <a href="22222/web/local"></a> <a href="/web/local"></a>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<a href="http:///web/locale/google.com">Link 1</a>
<a href="http:///web/locale/stackoverflow.com">Link 2</a>
<script>
var string = '/web/locale/';
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
var link = links[i].getAttribute('href');
link = link.replace(string, '');
links[i].setAttribute('href', link);
}
</script>
</body>
</html>
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.