我有一个用例,其中我必须选择所有<a>
,并在url中包含“ / web / local”之类的字符串,并从所有这些链接的href中删除“ / web / local”。 >
注意:我不能使用jQuery。我可以使用纯js或YUI。
谢谢。
答案 0 :(得分:1)
查看内联评论:
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>
答案 1 :(得分:1)
为了正确获取/ set href属性,您需要使用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>
答案 2 :(得分:0)
<!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>