Reputation: 9823
I have a page with a bunch of paragraphs. Each paragraph has an href that i want. However I dont want ALL the hrefs on the page, just the ones in the body ->p ->href.
How can I do this in javascript?
I want to do something like this, but it is wrong:
var myList = document.body.getElementsByTagName("p.href");
Note: I don't want to have to iterate over all p elements and extract the href, I just want to limit the scope of the hrefs.
sample input:
<p> <a href....></a></p>
Upvotes: 0
Views: 312
Reputation: 318372
In newer browsers :
document.querySelectorAll('p a[href="someLink"]')
or
var p = document.getElementsByTagName('p'),
arr = [];
for (var j=p.length; j--;) {
var a = p[j].getElementsByTagName('a'),
for (var i=a.length; i--;) {
arr.push( a[i].href );
}
}
Upvotes: 2
Reputation: 7309
Well as @j08691 stated if your p
elements have a href attribute they are invalid.
The following will get the href of an item where 0
is the index of an item
document.body.getElementsByTagName("p")[0].href
Upvotes: 0
Reputation: 10014
Assuming you have links (<a>
tags inside the <p>
elements)...
You can do it with jquery like this:
var links = $('p a');
or like this if you want only direct children (not further descendants):
var links = $('p > a');
Or with pure javascript you'd have to loop through:
var paragraphs = document.body.getElementsByTagName("p");
for (var i=0;i<paragraphs .length;i++)
{
var links = paragraphs[i].getElementsByTagName("a");
// This is only the links in this paragraph, so you would need to add to a global list if you want to keep track of all of them in one place
}
If you want to get the href attribute from a link element, you can do it like this:
var link0href = links[0].href;
Upvotes: 0