1

Here is jQuery cloned object in console log. Marked text is what I would like to get as string

enter image description here

Is that actual object name or something FireBug/jQuery has generated?

henrijs
  • 1,010
  • 2
  • 11
  • 19

2 Answers2

1

There is not a built in way to get that value (which is a CSS selector that would include that element). Firebug is simply creating a preview for you.

But it's not hard to put together yourself.

var toSelector = function(element) {

  // start with the tag name
  var result = element.tagName.toLowerCase();

  // append #theid, if the element has an id
  if (element.id) {
    result += '#' + element.id;
  }

  // append .theclass for each class the element has
  if (element.className) {
    var classes = element.className.split(' ')
    for (var i = 0; i < classes.length; i++) {
      result += "." + classes[i];
    }
  }

  return result;
}

var element = document.getElementById('foo');
alert(toSelector(element));

Working example: http://jsfiddle.net/uzrxJ/1/

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • Accepting answer. I could get each of these values separatly, but could not relive jQuery wasn't kind enough to add this info to object. I found there is another approach to include selector in .data(), but that included all selectors as one string. Will play around this little more... – henrijs Aug 16 '13 at 06:00
  • Also, in jQuery case, if data is located in element.context, not element itself. So your solution works when for example 'element.tagName.toLowerCase();' is modified to 'element.context.tagName.toLowerCase();' (also rest of appearances of 'element' in function). – henrijs Aug 16 '13 at 06:29
0

It's the selector for the element, used in firebug to visualize the object(the real value of target will be a reference to the Node)

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201