-2

Any ideas how to fix this error: "document.getElementByClassName is not a function"

Code below:

HTML:

<a href="#" class="filter-btn" onclick="myFunction()" data-filter="opd-list-id-<?php echo $item->ID; ?>" style="background:<?php echo $filter_background_color ?>;color:<?php echo $filter_text_color ?> !important;">

JS

function myFunction() {
var elmnt = document.getElementByClassName("filter-btn");
elmnt.scrollIntoView(); 
}
Icon
  • 911
  • 1
  • 10
  • 31
  • 3
    You're looking for `getElementsByClassName`. Note the "s" on Elements – Nick Nov 11 '19 at 19:29
  • @Nick noticed the same thing right away +1 – sao Nov 11 '19 at 19:35
  • 1
    If you have an error message then the first thing you should do is to search for that error, and check if there is already a question targeting that problem. And if that one does not help you to solve the problem then you should explain why. – t.niese Nov 11 '19 at 19:54

2 Answers2

1

Replce getElementByClassName with getElementsByClassName

note that its plural(Elements) with "s" at end and not singular(Element)

the same class can be added to multiple objects hence, selecting by class name returns multiple items, not just one so it uses the plural form Elements instead of Element as in case of getElementById() as id must be unique and selecting by id will return only one DOM element

and, since the function getElementsByClassName returns an array of elements elmnt.scrollIntoView() won't work,
so you need to use the first element of the array as elmnt[0]

so you code will be

function myFunction() {
  var elmnt = document.getElementsByClassName("filter-btn");
  elmnt[0].scrollIntoView(); 
}

However, I would rather suggest using getElementById if you want to select only one element and use as below(first give id IdGivenToTheAnchoreTag to anchor tag)

function myFunction() {
  var elmnt = document.getElementById("IdGivenToTheAnchoreTag");
  elmnt.scrollIntoView(); 
}
Shankar
  • 2,890
  • 3
  • 25
  • 40
0

You're looking for getElementsByClassName. Note the "s" on Elements

function myFunction() {
  var elmnt = document.getElementsByClassName("filter-btn");
  test.scrollIntoView();  
}
Nick
  • 16,066
  • 3
  • 16
  • 32