Known ID
$(".container > #first");
or
$(".container").children("#first");
or since IDs should be unique within a single document:
$("#first");
The last one is of course the fastest.
Unknown ID
Since you're saying that you don't know their ID top couple of the upper selectors (where #first
is written), can be changed to:
$(".container > div");
$(".container").children("div");
The last one (of the first three selectors) that only uses ID is of course not possible to be changed in this way.
If you also need to filter out only those child DIV
elements that define ID attribute you'd write selectors down this way:
$(".container > div[id]");
$(".container").children("div[id]");
Attach click handler
Add the following code to attach click handler to any of your preferred selector:
// use selector of your choice and call 'click' on it
$(".container > div").click(function(){
// if you need element's ID
var divID = this.id;
cache your element if you intend to use it multiple times
var clickedDiv = $(this);
// add CSS class to it
clickedDiv.addClass("add-some-class");
// do other stuff that needs to be done
});
CSS3 Selectors specification
I would also like to point you to CSS3 selector specification that jQuery uses. It will help you lots in the future because there may be some selectors you're not aware of at all and could make your life much much easier.
After your edited question
I'm not completey sure that I know what you're after even though you've written some pseudo code... Anyway. Some parts can still be answered:
$(".container > div[id]").each(function(){
var context = $(this);
// get menu parent element: Sub: Show Grid
// maybe I'm not appending to the correct element here but you should know
context.appendTo(context.parent().parent());
context.text("Show #" + this.id);
context.attr("href", "");
context.click(function(evt){
evt.preventDefault();
$(this).toggleClass("showgrid");
})
});
the last thee context
usages could be combined into a single chained one:
context.text(...).attr(...).click(...);
Regarding DOM elements
You can always get the underlaying DOM element from the jQuery result set.
$(...).get(0)
// or
$(...)[0]
will get you the first DOM element from the jQuery result set. jQuery result is always a set of elements even though there's none in them or only one.
But when I used .each()
function and provided an anonymous function that will be called on each element in the set, this
keyword actually refers to the DOM element.
$(...).each(function(){
var DOMelement = this;
var jQueryElement = $(this);
...
});
I hope this clears some things for your.