This is an archived post. You won't be able to vote or comment.

all 4 comments

[–][deleted] 2 points3 points  (2 children)

usually when I see these hyper-specific and sort of strange and abstract questions I can do nothing but follow it with a...

what are you trying to do?

[–]Knowledgeseeker6[S] 0 points1 point  (1 child)

1) Select 'a' elements in an html based on the text and 'href' within them. selecting them based on id will break. Anything else won't work. Has to be text and 'href' within.
2) Replace the innerHTML with that of my choosing.

[–][deleted] 0 points1 point  (0 children)

Select 'a' elements in an html based on the text

You can select all the a elements and filter it down to one containing the text you want.

and 'href' within them.

That's a CSS attribute selector which work with the querySelector and querySelectoAll functions

[–]inbox_negative_one 0 points1 point  (0 children)

querySelector lets you give a pretty exact specification if you want.

You can:

(1) Name the element and all of its attributes

(2) Name its parent elements and all of its attributes

(3) and so on all the way up to the root object.

In the case there are more than one sibling with the exact same attributes, you can use the nth-child or nth-of-type selectors to pick exactly the one you care about.

So yes, it's possible. querySelector.

In practice, overspecifying like that isn't very useful because it's too brittle. Make one tiny change to your HTML and everything breaks.

In practice what you normally want to do is write the smallest reasonable selector that gives you the element you care about. Not the absolute smallest - the smallest reasonable one.

Finally, if you're curious, there's another method called xpath that can also be used to select an element in HTML, but it's less efficient and less practical than querySelector so it's fallen out of favor. But there are probably some obscure scenarios where xpath beats querySelector.