I need to get all href link values using javascript. I have this code,
<body onload="myFunction()">
<div class="pull-right">
<a class="download-link" id="download_link" href="%file_url%">Download</a>
</div>
</body>
It shows like this
<a class="download-link" href="http://mysite.com/download/myfiles/file1.pdf">Download</a>
<a class="download-link" href="http://mysite.com/download/myfiles/file2.docx">Download</a>
<a class="download-link" href="http://mysite.com/download/myfiles/file3.zip">Download</a>
<a class="download-link" href="http://mysite.com/download/myfiles/file4.html">Download</a>
but if I used a native javascript like on the code below, only the first item is shown.
<script type="text/javascript">
function myFunction()
{
var url = document.getElementById("download_link").href;
var ext = url.split('.').pop();
alert(ext);
}
</script>
Why I'm getting only one output when I used a javascript to display the items? I tested it using their file extensions since I splitted the files. Any Idea What is missing on the javascript? I just want to continuously display(Alert) the items. My problem is, It only display the first item.
You can get a NodeList of all a elements using document.getElementsByTagName. That list has a length, and you can index into it with []. E.g.:
var links = document.getElementsByTagName('a');
var i;
for (i = 0; i < links.length; ++i) {
// Do something with links[i].href
}
On modern browsers, if you wanted to limit that further (for instance, only links with the download-link class on them), you can use querySelectorAll, which accepts a CSS selector:
var links = document.querySelectorAll('a.download-link');
// ...and then use it the same way as above
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With