开发者

JavaScript hide another element on mouseover

开发者 https://www.devze.com 2023-02-11 05:13 出处:网络
So I have this JavaScript I am working on, and I want to show/h开发者_运维技巧ide another HTML element on mouseover but it wont work.

So I have this JavaScript I am working on, and I want to show/h开发者_运维技巧ide another HTML element on mouseover but it wont work. Here's The HTML:

<div class='post' onmouseover="document.getElementsByClassName('another_element').style.display='inline';" onmouseout="document.getElementsByClassName('another_element').style.display='none';">


Try this:

<div class='post' onmouseover="document.getElementsByClassName('another_element')[0].style.display='inline';" onmouseout="document.getElementsByClassName('another_element')[0].style.display='none';">

It doesn't work because getElementsByClassName() retrieves an array of elements that contain another class. You just have select which element you want.

If the element is only one, you could give it a certain id, like this:

<div id="another_element"></div>

<div class='post' onmouseover="document.getElementById('another_element').style.display='inline';" onmouseout="document.getElementById('another_element').style.display='none';">


I just had a thought, and found a simple solution. Thanks all of you guys for your contributions. Here's what I came up with. I can set a unique id to each element I am going to show/hide, and use getElementById for each one instead of using the getElementsByClassName and having to loop through the array. So It ends up like this:

onmouseover="document.getElementById('an_element').style.display='inline'; document.getElementById('another_element').style.display='inline';"
onmouseout="document.getElementById('an_element').style.display='none'; document.getElementById('another_element').style.display='none';"


getElementsByClassName returns an array. Try iterating over them.


getElementsByClassName returns a NodeList, not a Node. A NodeList does not have a style property. You can either use the first element in the list only, or you could select by ID instead:

<div class='post' onmouseover="document.getElementsByClassName('another_element')[0].style.display='inline';" onmouseout="document.getElementsByClassName('another_element')[0].style.display='none';">

<div class='post' onmouseover="document.getElementsById('another_element').style.display='inline';" onmouseout="document.getElementsById('another_element').style.display='none';">

Obviously in the second example you need to give the element an ID...

0

精彩评论

暂无评论...
验证码 换一张
取 消