0

I am trying to work out how to select a container by a link contained within it. It looks something like this:

<div>
  <p>Some text here</p>
  <a href="www.test.com">My Link</a>
</div>

I know the value of "My link". However, the div has no ID or class and is not contained within anything except the body.

How could I use javascript to select the div element so I can manipulate it? I've found ways to select the link using the DOM but not the outer div. There are many divs on the page, so I cannot just select div.

Your help is appreciated!

Liam
  • 27,717
  • 28
  • 128
  • 190
  • *"...and is not contained within anything except the body..."* It is in your example. It's contained in a `div`. Is that accurate re your real situation? – T.J. Crowder Oct 25 '19 at 10:25
  • 1
    or possibly better target [Getting the parent div of element](https://stackoverflow.com/questions/6856871/getting-the-parent-div-of-element) – Liam Oct 25 '19 at 10:27
  • 1
    @Liam - To me the question is more about finding the `a` element. (Wouldn't be surprised if there's a dupetarget for *that*, though, too...haven't immediately found one, but...) – T.J. Crowder Oct 25 '19 at 10:29
  • yeah, not actually that clear now I re-read it. Hey hoooo – Liam Oct 25 '19 at 10:35

1 Answers1

3

If the only thing you know is that it's a a as a direct child of a div and it contains the text My Link, you can find it by finding all div > a elements and picking the first one that has that text:

const a = [...document.querySelectorAll("div > a")].find(a => a.innerText === "My Link");

(That relies on the fact that NodeList become iterable a couple of years ago; you may need to polyfill that.)

a will now be the first matching a element, or null if none matched.

From there, if you want that element's container, you can use closest with a CSS selector. For instance:

const x = div.closest("CSS selector here");

...or just use parentNode/parentElement as needed.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875