menteith menteith - 1 month ago 9
CSS Question

How do I get the content of <a href> when I know only the name of the next tag?

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>

Answer

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.


Based on your comment, this will change the header's text content to match its parent's href:

var h2 = document.querySelector('h2');
h2.textContent = h2.parentElement.getAttribute('href')
Comments