Here is a function to get the CSS selector from an element:
var getElementSelector = function($el) {
var selector = $el.get(0).tagName.toLowerCase();
var id = $el.attr('id');
var cssClass = $el.attr('class');
if (id) selector += '#' + id;
if (cssClass) selector += '.' + cssClass.replace(/ /g, '.');
return selector;
};
If you have the following element in a jQuery object:
<span id="identifire" class="link-wrap">
And this jQuery object was:
$mySpan
Calling the function:
getElementSelector($mySpan)
Would return the string:
span#identifire.link-wrap
Here is another function to get the full CSS path of the element:
var getElementSelectorPath = function($el) {
var path = getElementSelector($el);
while($parent = $el.parent()) {
var selector = getElementSelector($parent);
if (selector.substr(0, 4) == 'html') return path;
path = selector + ' > ' + path;
$el = $parent;
}
};
Note that this function has a dependency on the previous function getElementSelector.
Passing $mySpan to this function:
getElementSelectorPath($mySpan)
Would return a string something like this:
body > div#content-wrap > div#home > p.intro > span#identifire.link-wrap
