Get a unique jQuery selector

I need to be able to select unqiue for each element on the page.

For example, when I click on an element, I want to do something like this:

$(document).click(function(){
    var sel = getUniqueSel(this);
});

So, after storing the value selin the DB, I can get this value and just access the element

var el = $(sel);

I cannot change and know nothing about the structure of the HTML page, and I cannot just add a unique identifier (using JS) for each element, as that would be inefficient.

+5
source share
2 answers

, dom , , , , , , .

: , ,

JSBin document. , .

jQuery.fn.getPath = function () {
    if (this.length != 1) throw 'Requires one element.';
    var path, node = this;
    if (node[0].id) return "#" + node[0].id;
    while (node.length) {
        var realNode = node[0],
            name = realNode.localName;
        if (!name) break;
        name = name.toLowerCase();
        var parent = node.parent();
        var siblings = parent.children(name);
        if (siblings.length > 1) {
            name += ':eq(' + siblings.index(realNode) + ')';
        }
        path = name + (path ? '>' + path : '');
        node = parent;
    }
    return path;
};
var sel;
$(document)
    .click(function (e, a) {
    if (!sel) {
        sel = $("#comment-21702402")
            .getPath();
        alert("Path is: " + sel + ", hiding the Element -> Click again to highlight");
    } else {
        $(sel)
            .css("background-color", "yellow");
    }
});
+6

- , , . , , , : , ,: <div> I'm a div </div>

$(document).click(function(){
    var tagName = $(this).prev().prop('tagName');
    var attributes = {}; 
    if( this.length ) {
        $.each( this[0].attributes, function( index, attr ) {
            attributes[ attr.name ] = attr.value;
        } ); 
    }
    var elText=$(this).html();
    saveToDB(tagName,attributes,elText);
});

, , ,

$(tagName+'['+attribute+'="'+value+'"]:contains("'+elText+'")')

,

0

All Articles