Hi there i am relatively new to javascript and i have been attempting to store hyperlinks with the <a>
tag into a array in javascript is there a elegant or simple way of doing this?
Asked
Active
Viewed 209 times
-3

Dr.Molle
- 116,463
- 16
- 195
- 201
-
2What you want is certainly do-able, but you're going to need to explain what you mean by, "hyperlinks with the tag." Moreover, showing a sample of your HTML and the JavaScript you've tried so far is a must. – JAAulde May 26 '15 at 21:46
-
2You'll probably have to add some code along with a few examples of things you tried in order to receive any help. You can always update your question. Welcome to stack overflow, recommended reading: http://stackoverflow.com/help/how-to-ask – Dan Beaulieu May 26 '15 at 21:47
-
2[`document.links`](https://developer.mozilla.org/de/docs/Web/API/Document/links) – Dr.Molle May 26 '15 at 21:48
-
I am not too sure how to word it. i just wish to search a site find all the download links that are there and display them. So i assumed you would have to search through the HTML code to find all the anchor tags "". – Matthew Jones May 26 '15 at 21:48
-
1@Dr.Molle — interesting... in Chrome developer tools just now, on _this_ page, `document.links` produced `HTMLCollection[199]` while `document.getElementsByTagName('a')` produced `HTMLCollection[215]` ... because some `` tags could be `` and **not** `` – Stephen P May 26 '15 at 21:59
-
@Matthew A link is a link ... what is a _"download link"?_ Only links to downloadable files, as opposed to links to other web pages? If that's it, how would you tell the difference? Also keep in mind that not all `` tags are links of any kind. – Stephen P May 26 '15 at 22:02
-
anchor tags aren't always links ... sometimes they are just placeholders. See this question: [Is an anchor tag without the href attribute safe?](http://stackoverflow.com/questions/5292343/is-an-anchor-tag-without-the-href-attribute-safe) – Yogi May 26 '15 at 22:03
-
also note that `document.links` also includes `` , to get only the `` you may use `document.querySelectorAll('a[href]')` – Dr.Molle May 26 '15 at 22:48
1 Answers
1
Hi you have this response: Get an array of list element contents in jQuery
You only need change
var links = [];
$("a").each(function() { links.push($(this).attr('href')) });
If you dont want to use jquery, nice!
You can do
var elements = document.getElementsByTagName('a'),
links = [];
for (var i = 0; i < elements.length; i++) {
links.push(elements[i].getAttribute('href'));
}

Community
- 1
- 1

Raúl Martín
- 4,471
- 3
- 23
- 42
-
1I believe in your first snippet you meant to use links instead of optionTexts, as optionTexts is not defined anywhere. – McCroskey May 26 '15 at 22:10