javascript - get element by class

Excluded anywhere else
Eric Miller
Posts: 1
Joined: Tue Mar 21, 2017 5:14 pm
Contact offline

javascript - get element by class

Post by Eric Miller » Tue Mar 21, 2017 5:26 pm

How to get element by class name in Javascript? How can I find a div by its class?

My code doesn't work:

Code: Select all

var JavascriptVariable = document.getElementByClassName("myClassName");

Juraj Vysvader
Site Admin
Posts: 45
Joined: Sat Aug 13, 2016 5:58 pm
Contact offline

Re: javascript - get element by class

Post by Juraj Vysvader » Wed Mar 22, 2017 10:44 pm

You didn't land on stackoverflow.com

Expectedly, if we have seen getElementById() Method, then we could try to write something like: "getElementByClassName()", however, it's not gonna work.
Thus, you should try getElementsByClassName(). More elements share the same class, so it's in plural, or in other case, it should be id.

Vanilla Javascript example:

Code: Select all

var JavascriptVariable = document.getElementsByClassName("myClassName");


jQuery examples:

Code: Select all

var JavascriptVariable = $(".myClassName");

Code: Select all

var JavascriptVariable = $("#parentDiv").find(".myClassName");

Code: Select all

var JavascriptVariable = $("#Div").hasClass("myClassName"); //boolean