Get unique selector jQuery

2020-02-29 01:26发布

I need to be able to get an unqiue selector for each element on a 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 sel value in a DB I can get that value and simply access the element by

var el = $(sel);

I can't change and don't know anything about the HTML structure of the page and I can't simply add unique ID's (using JS) to every element as this would be inefficient.

2条回答
一夜七次
2楼-- · 2020-02-29 01:44

Another approach might be to wander up the dom tree and create a path to the element, which you can save and use it later as a selector again, although that might not be bulletproof, but maybe its a point where you can start off.

Edit: Updated the Answer with your suggestion in the comment, now it returns the id if available

Just visit the example on JSBin And click the document twice. but notice what gets highlighted..

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");
    }
});
查看更多
beautiful°
3楼-- · 2020-02-29 02:00

One way to do this is to get all the information you can get on the element that was clicked. So when you save it to the database you can save it as a text for example: If the element you clicked on is: <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);
});

You can later find the element using the attributes you have or simply use

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

I think this should help

查看更多
登录 后发表回答