1

i'm currently having issue with the getElementsByClassName property. I have a show and hide function which displays a button when you hover over the product click here I have enabled this function using the getElementById property, however due to the fact i want to duplicates of this function using a class is better practice. Is the code below the correct way to address this problem using the ClassName JS function?

Also i've been reading getElementsByClassName is not supported in IE8 is this true and is there a way to work around this?

  <script>    
  function show(viewProductBtn){
document.getElementByClassName(viewProductBtn).style.visibility = "visible";
}

function hide(viewProductBtn) {
document.getElementByClassName(viewProductBtn).style.visibility = "hidden";
}
</script>

<!--HTML-->
<div class="product-shot-bg" onMouseOver="show('viewProductBtn')"      onMouseOut="hide('viewProductBtn')">
        <a href="#" class="viewProductBtn"></a>

at present i've switched the my dev site back to getByID to demonstrate how the transition should work..

NewBoy
  • 1,124
  • 2
  • 17
  • 40
  • Yes IE doesn't support getElementsByClassName. You can get around this by either rolling your own function that walks the dom and grabs all elements with the same class OR you take the easy way and employ some sort of library that already has it implements such as jQuery OR you use id's. Not certain what you mean you want to duplicate the function? You realize that if you copy the function you are just redefining it? – scrappedcola Sep 11 '12 at 20:57
  • @scrappedcola added getElementsByClassName in IE9. – Niet the Dark Absol Sep 11 '12 at 21:02
  • I shouldn't use the word duplicate.. it's more a loops for when i integrate the site into a cms – NewBoy Sep 11 '12 at 21:03

1 Answers1

6

getElementsByClassName

"Elements" in the plural. Meaning, the function returns an array (actually a NodeList), so you need to either loop through the array, or get the first element if you only want that one.

See also document.querySelector("."+viewProductBtn) for one element, document.querySelectorAll("."+viewProductBtn) for multiple, or consider using IDs and getElementById.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592