Let’s say I have a section with an anchor tag. Is it possible to target another element on the page outside of that anchor tag’s parent?
For example, when a user hovers over the anchor tag in the following code, the paragraph tag inside of another container gets targeted, whether it’s changing the font size, color, whatever, etc. Any suggestions or guidance would be much appreciated!
<div class="container">
<div>
<ul>
<li><a href="#">hover me</a><li>
</ul>
</div>
</div>
<div class="target-container">
<p id="target-element">Target Element</p>
</div>
Seems like there has to be a way to do this with js, as css won’t work obviously since the target element is outside of the container.
3
Answers
Some ways to select elements include
document.querySelector
anddocument.getElementById
.In this case, you can add event listeners for
"mouseenter"
and"mouseleave"
on the anchor element, and change or revert the styles of the other element in those event handlers, respectively.In addition to the other answer and comments, this can also be achieved with just CSS.
NOTE: The
:has
CSS Pseudo-class does not work in Firefox for Android.With modern CSS yes You can do this with has and a general sibling selector. Check browser
has()
support to see if it meets your needs.