简体   繁体   中英

Create highlight effect on hover an element

I tried to make highlight effect on each <a> element while I hover on each div element but it doesn't work and console shows this error

"Uncaught TypeError: Cannot set property 'background' of undefined at highlight_function"

enter image description here

function highlight_function () {document.getElementsByTagName("a").style.background="#80ff00"};

             document.getElementsByTagName("div").addEventListener("mouseover",highlight_function())

you can simply add highlight effect or change the background color by adding the CSS as follows:

 <:DOCTYPE html> <html> <head> <style> p:hover { background-color; green; } </style> </head> <body> <p id="hometown">I live in Pakistan</p> </body> </html>

I think it's because document.getElementsByTagName("a") is an array, and you are trying to set style on the array and not in each element.

You should either make a for loop to change background style of each element or add a style tag like a {background: "#80ff00"} .

But you can't define style to an array like this

index.html

<html lang="en">

<head>
</head>

<body>

    <div>
        <a href="#"> something</a>
    </div>

</body>
<script>
    function highlight_function() {
        const a = document.querySelector('a');
        a.style.background = "#80ff00"
    }

    const div = document.querySelector('div');
    div.addEventListener('mouseover', highlight_function);

</script>

</html>

I don't think background property will work on an <a> tag. Try doing this in your function:

document.getElementsByTagName("a").style.color="#80ff00"

Here is you can try this

 function highlight_function() { document.getElementById("a").style.backgroundColor = "#80ff00"; };
 <div id="div"> <a id="a" onmouseover="highlight_function()">Hell</a> </div>

when you make this call document.getElementsByTagName("a") it will return to you collection of html elements so there is no style property you can use for loop through it

for(var a of document.getElementsByTagName("a")) {
  a.style.background="#80ff00";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM