Popa Andrei
Popa Andrei

Reputation: 338

jQuery get element by class

I'm currently using a script called clamp.js to cut some text, and it currently selects it by ID. I want to use it so it selects by class. The script is like this:

var module = document.getElementById("clampjs");

How can I modify that line so it selects a certain "test" div class? thanks.

Upvotes: 4

Views: 36369

Answers (3)

Felix
Felix

Reputation: 38102

You can use getElementsByClassName():

var module = document.getElementsByClassName("test")[0];

With jQuery, you can use class selector:

var module = $('.test');

Upvotes: 6

Rickert
Rickert

Reputation: 1675

$('.Class') to get al class element $('#id') To get an id element

Upvotes: 0

user632287
user632287

Reputation:

Is this supposed to be marked as jQuery or JavaScript?

jQuery:

var module = $("#clampjs"); // by id
var module = $(".clampjs"); // by classname

JavaScript:

var module = document.getElementById("clampjs"); // by id JS version
var module = document.getElementsByClassName("campjs"); // by class JS version

You might want to read up on jQuery: http://www.jquery.com if that is what you meant to do!

Upvotes: 15

Related Questions