htmlurlhyperlinkuriuri-fragment

Can an URL fragment point to a HTML element that has no id?


I'd like to provide a link to an external page (not under my control) that has a specific part where I want it to point to (it's a license page with an appendix, and I want the link to go directly to the appendix).

I would normally do this with a # in the URL, like this: https://en.wikipedia.org/wiki/Fragment_identifier#Examples

This makes the page scroll to already start on the HTML element with id="Examples".
The problem is when the HTML page doesn't put an id on the elements.

Is there any other way to make the URL point to the relevant section? Do URL fragments accept only ids or can I use other CSS selectors somehow?


Solution

  • It doesn't seem you can use CSS selectors (missed opertunity I think) but you can use Text Fragments to scroll to and highlight text content on the page.

    From the MDN page:

    Usage

    https://example.com#:~:text=[prefix-,]textStart[,textEnd][,-suffix]

    Examples

    https://example.com/#:~:text=for scrolls to and highlights the first instance of the text for in the document.

    https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/a#:~:text=human,URL scrolls to and highlights the first instance of a text string starting with human and ending with URL.

    https://example.com/#:~:text=asking-,for scrolls to and highlights the second instance of the text for in the document.

    https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/a#:~:text=Causes&text=linked scrolls to and highlights the first instances of the text strings Causes and linked.

    https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/a#:~:text=linked%20URL,-'s%20format&text=Deprecated-,attributes,attribute scrolls to and highlights two text instances:

    • The first instance of the text linked URL that has the text 's format directly following it.
    • The first instance of a text string starting with attributes and ending with attribute, which is prefixed by Deprecated.

    My own example that made me stumbple accross this: https://www.kernel.org/doc/html/latest/input/multi-touch-protocol.html#:~:text=ABS_MT_TOOL_TYPE,-the points to the 3rd instance of ABS_MT_TOOL_TYPE