In the DOM I have several Elements which have no ID, but instead an CSS class assigned. Like this:
<td class="foobar">...</td>
How could I access this element easily with jQuery?
In the DOM I have several Elements which have no ID, but instead an CSS class assigned. Like this:
<td class="foobar">...</td>
How could I access this element easily with jQuery?
$('.foobar')
gets you an array of all elements with that class.
But seriously, RTFM. http://docs.jquery.com/Selectors/class#class
jQuery uses CSS Selectors.
So, your selector would be the same as how you access the item when writing CSS styles for it.
$('.foobar') //selects elements with class "foobar"
$('#foobar') //selects elements with the id "foobar"
$('div.foobar') //selects divs with the class "foobar"
etc.
More at: http://docs.jquery.com/Selectors
You need a ID on your object, else all objects with "foobar" will affected. Try:
<td class="foobar" id="myFoobar">...</td>
then access with $("#myFoobar)
The first answer of everyone will be $(".foobar")
or $("td.foobar")
But there is a better way to select element/s
especially when you are selecting them by there class.
By providing a context to the selector, you give it an element to start searching within so that it doesn't have to traverse the whole of the DOM.
in this case you write
$(".foobar", $("table"))
The simplest approach would be to do this:
$(".foobar")
However, it's not necessarily the fastest approach. This will return every element in the DOM with the class "foobar". But behind the scenes it's having to traverse through every single element in the DOM to get this list of elements.
Selecting elements with CSS classes through Javascript has always been an inherently slow operation (especially in large pages). Albeit, if you're only doing this once then we're probably talking about imperceivable milliseconds most of the time, but there is a faster way. As a rule of thumb, using an id in a CSS or jQuery selector is much faster than specifying a class. So whenever possible, use an id to narrow the number of elements the Javascript has to traverse. For example, if you had an id on the table like this:
<table id="mytable">
<tr>
<td class="foobar">
</td>
</tr>
</table>
Then you could do something more like this utilizing the optional context parameter:
$(".foobar", "#mytable")
This will search for all elements with a class of foobar inside mytable. And this should take considerably less time to do. There could easily be a 2X speed improvement or more depending on the relative size of the context compared to the rest of the page.
Resources: