user2600677
user2600677

Reputation:

Getting an Element of a Particular Class

Is it possible to get an element with a particular class solely by using the class name? For example, if I have:

<div class="hello"> Hello World! </div>  

Is there a method in jQuery that accepts a parameter hello and returns the div(s) that have class "hello"?

I know that I can use a for loop until I find a given div with the class/id-name, but I was just curious if there was anything else.

Upvotes: 0

Views: 92

Answers (4)

Kjeld Schmidt
Kjeld Schmidt

Reputation: 768

I give you an answer, under the condition, that you show me the for loop you could use, because I have no idea how that would work. Also interesting: How is "select an element by it's class" not the very first thing you learned with jQuery? What can you even do without that?

Anyway:

$(".hello");

Selects everything of class "hello".

Upvotes: 0

John
John

Reputation: 166

$(".hello")

The JQuery class selector will select everything with the class "hello".

http://api.jquery.com/class-selector/

Upvotes: 1

Sam Hanley
Sam Hanley

Reputation: 4755

Since everyone's just throwing out the jQuery solution to the question, it's worth noting that selecting elements is one of the most basic JavaScript concepts so it's absolutely possible to do it without jQuery as well. You'd use the JavaScript document.getElementsByClassName function, which is well documented at the Mozilla Developer Network.

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

Yes, the class selector .

$("div.hello") //Div's with class of hello

Or

$(".hello") //All elements with class of hello

Upvotes: 1

Related Questions