3

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:

devtools inspector

and in the console:

devtools 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...

GreatBlakes
  • 3,971
  • 4
  • 20
  • 28
  • Don't know the goal of this, but the returned selector isn't unique to that element if there is no `id` attribute. That makes the function name a bit misleading or ambiguous. – Randy Casburn May 25 '19 at 19:21
  • Good point. In this use case non-unique selectors won't be a problem, but I will keep that in mind to improve the function name, thanks. – GreatBlakes May 25 '19 at 19:23
  • What _is_ the use case? You already have a reference to the Object. Why the need for a selector? – Randy Casburn May 25 '19 at 19:23
  • If xpath works for you , there is this answer that returns xpath - https://stackoverflow.com/a/2631931/301303 – vittore May 25 '19 at 19:24
  • This is for detecting and logging possible UX issues. This part of the functionality is simply showing a *general* guide of what the problematic element was. – GreatBlakes May 25 '19 at 19:25
  • 1
    Have a look at this: http://stackoverflow.com/questions/2420970/how-can-i-get-selector-from-jquery-object/15623322#15623322 – Kravimir May 25 '19 at 20:54
  • Thanks @Kravimir that is a great reference. – GreatBlakes May 25 '19 at 21:22

0 Answers0