Reputation: 61
I have the following:
<a id="sample"></a>
I want to change this to:
<a href="https://www.exampledomain/testpage.aspx#sample"></a>
using either jQuery or plain JavaScript. The "sample" is a non-unique, dynamic attribute, but the domain I need to 'pre-pend' to it is always the same value. Thank you in advance.
Upvotes: 2
Views: 1505
Reputation: 186
const a = $("a");
const id = a.attr("id")
const host = "https://www.exampledomain/testpage.aspx#"
a.attr("href", `${host}${id}`)
Upvotes: 0
Reputation: 1
You can set the href before and then removing the attribute id
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Titre de la page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="sample">Sample</a>
<a id="xxx">Sample xxx</a>
<script>
$(document).ready(function() {
function changeId(id){
console.log(id);
var a = document.getElementById(id);
a.href = "https://www.exampledomain/testpage.aspx#"+id;
$('#'+id).removeAttr('id');
};
changeId("sample");
changeId("xxx");
});
</script>
</body>
</html>
Upvotes: 0
Reputation: 44086
Try .querySelectorAll()
and .forEach()
. This demo adds href
, text, and title
(shows full href
value when user hovers over a link)
var linx = document.querySelectorAll('a');
linx.forEach(lnk => {
let ID = lnk.id;
const host = 'https://example.com/#';
lnk.href = host + ID;
lnk.title = host + ID;
lnk.textContent = ID;
});
a {
display: block
}
<a id="ID0"></a>
<a id="ID1"></a>
<a id="ID2"></a>
<a id="ID3"></a>
<a id="ID4"></a>
<a id="ID5"></a>
<a id="ID6"></a>
<a id="ID7"></a>
<a id="ID8"></a>
<a id="ID9"></a>
<a id="IDA"></a>
<a id="IDB"></a>
<a id="IDC"></a>
<a id="IDD"></a>
<a id="IDE"></a>
<a id="IDF"></a>
Upvotes: 1
Reputation: 68
Here's a jQuery solution. If you don't need this for every single link, you should update the anchor variable to use a class or other selector.
var anchor = $("a");
var anchorTarget = "#" + anchor.attr("id");
var link = "https://www.exampledomain/testpage.aspx";
anchor.attr("href", link + anchorTarget);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<a id="sample">Test</a>
Upvotes: 1