Reputation: 181
How would I access(throught JavaScript) an anchor element without it having any attributes except "href"?
Example: <a href="http://www.example.com/forum/addPost/id=5"
Okay, now the "id" in the URL changes, so can I use like substr()
, or something else to "cut" the href attribute value in half. So it would now be href="http://www.example.com/forum/addPost/id="
.
Now what if there were multiple anchor tags on the page, how would I 'access' the anchor tag with the specific href?
Upvotes: 1
Views: 309
Reputation: 147513
There is a document.links collection that is all the links in the document, so:
var links = document.links;
var re = /www\.example\.com\/forum\/addPost/;
for (var i=0, iLen=links.length; i<iLen; i++) {
if (re.test(links[i].href)) {
// do stuff with the href value
}
}
Upvotes: 1
Reputation: 2288
If you are not opposed to using jQuery, this is pretty straightforward. To access a hyperlink if you have the ID value to search with:
var $anchor = $('a[href$="<ID value>"]');
The $anchor object would be a reference to the DOM element whose href ends with the ID that you specify.
Upvotes: 2