javascript - How to get element by class name? -


this question has answer here:

using javascript, can element id using following syntax:

var x=document.getelementbyid("by_id"); 

i tried following element class:

var y=document.getelementbyclass("by_class"); 

but resulted error:

getelementbyclass not function 

how can element class?

the name of dom function getelementsbyclassname, not getelementbyclassname, because more 1 element on page can have same class, hence: elements.

the return value of nodelist instance, or superset of nodelist (ff, instance returns instance of htmlcollection). @ rate: return value array-like object:

var y = document.getelementsbyclassname('foo'); var anode = y[0]; 

if, reason need return object array, can easily, because of magic length property:

var arrfromlist = array.prototype.slice.call(y); //or per antonb's comment: var arrfromlist = [].slice.call(y); 

as yckart suggested queryselector('.foo') , queryselectorall('.foo') preferable, though, are, indeed, better supported (93.99% vs 87.24%), according caniuse.com:


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -