"document.getElementByClass is not a function"
561710 просмотра
8 ответа
I am trying to run a function onclick
of any button with class="stopMusic"
. I'm getting an error in Firebug
document.getElementByClass is not a function
Here is my code:
var stopMusicExt = document.getElementByClass("stopButton");
stopButton.onclick = function() {
var ta = document.getElementByClass("stopButton");
document['player'].stopMusicExt(ta.value);
ta.value = "";
};
Автор: user547794
Источник
Размещён: 13.11.2019 11:31
Ответы (8)
233 плюса
You probably meant document.getElementsByClassName()
(and then grabbing the first item off the resulting node list):
var stopMusicExt = document.getElementsByClassName("stopButton")[0];
stopButton.onclick = function() {
var ta = document.getElementsByClassName("stopButton")[0];
document['player'].stopMusicExt(ta.value);
ta.value = "";
};
You may still get the error
document.getElementsByClassName
is not a function
in older browsers, though, in which case you can provide a fallback implementation if you need to support those older browsers.
Автор: BoltClock Размещён: 20.09.2011 05:2314 плюса
As others have said, you're not using the right function name and it doesn't exist univerally in all browsers.
If you need to do cross-browser fetching of anything other than an element with an id with document.getElementById()
, then I would strongly suggest you get a library that supports CSS3 selectors across all browsers. It will save you a massive amount of development time, testing and bug fixing. The easiest thing to do is to just use jQuery because it's so widely available, has excellent documentation, has free CDN access and has an excellent community of people behind it to answer questions. If that seems like more than you need, then you can get Sizzle which is just a selector library (it's actually the selector engine inside of jQuery and others). I've used it by itself in other projects and it's easy, productive and small.
If you want to select multiple nodes at once, you can do that many different ways. If you give them all the same class, you can do that with:
var list = document.getElementsByClassName("myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
and it will return a list of nodes that have that class name.
In Sizzle, it would be this:
var list = Sizzle(".myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
In jQuery, it would be this:
$(".myButton").each(function(index, element) {
// element is a node with the desired class name
});
In both Sizzle and jQuery, you can put multiple class names into the selector like this and use much more complicated and powerful selectors:
$(".myButton, .myInput, .homepage.gallery, #submitButton").each(function(index, element) {
// element is a node that matches the selector
});
Автор: jfriend00
Размещён: 20.09.2011 05:45
10 плюса
Before jumping into any further error checking please first check whether its
document.getElementsByClassName() itself.
double check its getElements and not getElement
Автор: neo Размещён: 18.06.2016 05:358 плюса
It should be getElementsByClassName
, and not getElementByClass
. See this - https://developer.mozilla.org/en/DOM/document.getElementsByClassName.
Note that some browsers/versions may not support this.
Автор: Saket Размещён: 20.09.2011 05:260 плюса
document.querySelectorAll
works pretty well and allows you to further narrow down your selection.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
Автор: KuN Размещён: 30.11.2016 04:380 плюса
you spelt it wrongly, it should be " getElementsByClassName ",
var objs = document.getElementsByClassName("stopButton");
var stopMusicExt = objs[0]; //retrieve the first node in the stack
//your remaining function goes down here..
document['player'].stopMusicExt(ta.value);
ta.value = "";
document.getElementsByClassName - returns a stack of nodes with more than one item, since CLASS attributes are used to assign to multiple objects...
Автор: Andaeiii Размещён: 19.02.2019 02:420 плюса
The getElementByClass
does not exists, probably you want to use getElementsByClassName
. However you can use alternative approach (used in angular/vue/react... templates)
function stop(ta) {
console.log(ta.value) // document['player'].stopMusicExt(ta.value);
ta.value='';
}
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 1'>
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 2'>
-1 плюса
enter code here
var stopMusicExt = document.getElementByClass("stopButton").value;
stopButton.onclick = function() {
var ta = document.getElementByClass("stopButton");
document['player'].stopMusicExt(ta.value);
ta.value = "";
};
// .value will hold all data from class stopButton
Автор: Gajender Singh
Размещён: 20.09.2016 04:29
Вопросы из категории :
- javascript Как определить, какой из указанных шрифтов был использован на веб-странице?
- javascript Валидация клиентской стороны ASP.Net
- javascript Длина объекта JavaScript
- javascript Получение текста из выпадающего списка
- javascript Скрипт входа со скрытыми кнопками
- javascript Как автоматически изменить размер текстовой области с помощью Prototype?
- javascript Удаление элементов с помощью Array.map в JavaScript
- javascript Прокрутка переполненных DIV с помощью JavaScript
- javascript API Карт Google - проблемы с классом GLatLngBounds
- javascript Проверка десятичных чисел в JavaScript - IsNumeric ()
- javascript Как я могу украсить код JavaScript с помощью командной строки?
- javascript Динамически загружать файл JavaScript
- javascript Экранирование строк HTML с помощью jQuery
- javascript Обнаружение неопределенного свойства объекта
- javascript Как сравнить HTML-сущность с JQuery
- javascript Есть ли HTML напротив <noscript>?
- javascript Есть ли функция "существует" для jQuery?
- javascript Как заставить клиентов обновлять файлы JavaScript?
- javascript Замена n-го экземпляра совпадения с регулярным выражением в Javascript
- javascript Сделать окно браузера мигающим в панели задач