While looking through JavaScript the event.target object, I can see all the typical parameters of the node- things like the nodeName, ID, and classes. However, I want to convert it to a string like h1.entry-title
for example.
I can see Chrome DevTools does this:
In the inspector:
and in the console:
Since I can't find the overall "selector" as a string, I figured I would need to do it myself. Here's what I came up with:
//Convert DOM objects into selector strings (tag#id.class)
function domObjectToSelector(object){
//If a jQuery object was passed, use the proper node
if ( !object.nodeType ){
object = object[0];
}
var selector = object.nodeName.toLowerCase();
if ( object.id ){
selector += '#' + object.id;
}
if ( object.className ){
selector += '.' + object.className.replace(/\s/g, '.');
}
return selector;
}
Is there a better way to do this, or does this seem like the right approach? It just feels like I'm over-engineering this...