Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get element by class

Tags:

jquery

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.

like image 514
Popa Andrei Avatar asked Nov 15 '25 16:11

Popa Andrei


2 Answers

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!

You can use getElementsByClassName():

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

With jQuery, you can use class selector:

var module = $('.test');
like image 22
Felix Avatar answered Nov 17 '25 07:11

Felix