Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Bryant Feld
Full Stack JavaScript Techdegree Student 26,144 PointsHow do I bind an event to one specific element of a specific class(without giving it it's own id)?
HTML - CSS - JavaScript - jQuery
2 Answers
Erik Nuber
20,629 Pointsyou can use querySelector or querySelectorAll.
var mySelection = document.querySelector(selector)
this would give you back the first item only of the selector
var mySelections = document.querySelectorAll(selector)
this would give you all items of the selector type
you can also use
var mySelections = document.getElementsByTagName(selector)
this would get all Tags by a certain name.
It is important to be as specific as you can with a selector as well.
for example if you wanted a specific class
var classSelected = document.querySelectorAll('li.hot');
here you would be getting all items that have a li tag that are of class hot.
Erik Nuber
20,629 PointsI noticed after I answered that it says jQuery from where the question originated.
In jQuery, it is much simpler
$(selector)
Thats it. You don't have to have an ID you can just enter a class or a specific tag like this
$('.className') //this would specify a specific className
$(':header') //this would specify all header tags from h1-h6
$('li:lt[3]') //this would specify the first three li tags in a list
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsHi Bryant,
Are you saying that you have multiple elements all with the same class and you need to target a specific one?
If so, I think we would need to see some example markup and which element you're trying to target.
There needs to be something unique about it.