CSS- Highlight a div when the id is linked to using an anchor? CSS- Highlight a div when the id is linked to using an anchor? javascript javascript

CSS- Highlight a div when the id is linked to using an anchor?


You need to use the :target pseudo-class:

:target {   background-color: #ffa;}

JS Fiddle demo.


You can do this in JavaScript. Refer to How to get the anchor from the URL using jQuery? on how to get the anchor from URL and then it can be something simple like

document.getElementById(hash).style.backgroundColor="Yellow";


JavaScript can be used to dynamically add/change the class of the div:

If you have:

<div id="test"></div>

Javascript function, executed by the click of the anchor:

document.getElementById("test").className += " highlighted";

Result:

<div id="test" class=" highlighted"></div>