Search code examples
javascriptphphtmlcsshighlight

How do I highlight text linked to from a separate webpage?


I have a web-page with anchor tags that are linked to specific words in another page that contain only the words.

Every single word in the words page is wrapped with an <a> anchor tag having a unique ID like this:

<a id="a">Капитанская</a>
<a id="b">дочкаБереги</a>
<a id="c">Капитанская</a>
<a id="d">дочкаБереги</a>

And in the web-page there are links to those words that look like this:

<a href="website.com/text-page.html#a">Капитанская</a>
<a href="website.com/text-page.html#b">дочкаБереги</a>

I need to find a way to highlight the word I'm linking to with a colored background or something like that.

I'm using JavaScript, HTML, CSS and PHP for both the webpages, and don't have the ability to use anything else.


Solution

  • On your text page, you can just retrieve the id from your url using the hash property from the window.location read-only property and assign a background color to the text element that has that id like this:

    //get the id from the URL
    const link = window.location.hash.split('#')[1];
    
    //add a class to the element that has that id
    document.getElementById(link).classList.add('highlighted');
    .highlighted {
      background-color: green; //add background color to that element
    }
    <a id="word1">word1</a>
    <a id="word2">word2</a>
    <a id="word3">word3</a>
    <a id="word4">word4</a>
    <a id="word5">word5</a>
    <a id="word6">word6</a>
    <a id="word7">word7</a>
    <a id="word8">word8</a>