You can just walk up the parent chain looking for an ancestor with the proper class. This version of the code allows there to be other class names on the object of interest so the code can be used more flexibly:
function hasClass(elem, cls) {
var str = " " + elem.className + " ";
var testCls = " " + cls + " ";
return(str.indexOf(testCls) != -1) ;
}
function closest(el, cls) {
while (el && el !== document) {
if (hasClass(el, cls)) return el;
el = el.parentNode;
}
return null;
}
So, from your click handler, you can just do:
var id;
var target = closest(this, "section");
if (target) {
id = target.id;
// do whatever you want with the id
}
Working demo: http://jsfiddle.net/jfriend00/6V7HG/
FYI, a version of this code that can take any arbitrary selector is much, much more complicated as you essentially have to create a CSS selector parser and then evaluate if a given object matches all the requirements in that selector. That is probably way more work than you would want to do for this particular operation.
Usually, you're not looking up a chain for an id because you can just get the element with that id directly so I've offered a version that works with a class name. Other versions (like one that matched an attribute) could also be written.
This version is a little more generic than your particular question (returning the target element rather than the target id) which allows you to use it in more circumstances. If you really just want a function that returns the target id, that can be done like this:
function closest(el, cls) {
while (el && el !== document) {
if (hasClass(el, cls)) return el.id;
el = el.parentNode;
}
return null;
}