I'd like to get the content of a href
using JavaScript (not jQuery). In the example I show below it is string some-link-here
.
I have tried various combinations of document.querySelector
such as
document.querySelector("h2").getElementsByTagName("a")[0=].previous.Sibling.textContent
but I cannot the string I want.
<td align='center' rowspan=2 valign='top'><a href='some-link-here'><h2>DOWNLOAD</h2>
If you know where exactly after how many anchor() tag your desirable tag is present, then you can use below code by just replacing array index (0 here)
document.getElementsByTagName('a')[0].getAttribute("href")
Otherwise you can use below code if you only know the child tag.
document.querySelector('h2').parentElement.getAttribute("href")
According to your requirement, if [H2] tag is not a child of [A] and just a next tag, you should try below code.
document.querySelector('h2').previousElementSibling.href
This gets the value of the href
:
document.querySelector('h2').parentElement.getAttribute('href')
The anchor (A) is the parent element of the header (H2) element.
var h2 = document.querySelector('h2'); h2.textContent = h2.parentElement.getAttribute('href')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.