Farnabaz
Farnabaz

Reputation: 4066

javascript find selector of an element

what i want is to detect which elements clicks by user and send those selector query to server
I don't want to use any library and want to do this only by javascript itself, my code listen document.onclick and I could get event.target and do some stuff in real time, but I want store this element selector query in server for future usage

document.onclick = function (event) {
    var target = event.target;
    var selector ; // 
}

how get event.target unique selector? and use this selector in document.querySelector and access to element

Upvotes: 2

Views: 2031

Answers (3)

Maarten Coppens
Maarten Coppens

Reputation: 199

If you want it to be very expressive you could do, or perhaps remove the else block.

const attributes = target.getAttributeNames();

let query = target.localName;

for (let i = 0; i < attributes.length; i++) {
  const a = attributes[i];
  const attrValue = target.getAttribute(a);
  if (!attrValue) return;

  if (a === 'id') {
    query += `#${attrValue}`;
  } else if (a === 'class') {
    query += `.${attrValue.split(' ').join('.')}`;
  } else {
    query += `[${a}="${attrValue}"]`;
  }
}

Upvotes: 0

Schnodderbalken
Schnodderbalken

Reputation: 3467

I built a function in Javascript without Jquery that creates a unique identifier for any element in the DOM. If it has an id it uses the id. Otherwise it creates a path based on the parents of that element:

function getSelector(node) {
    var id = node.getAttribute('id');

    if (id) {
        return '#'+id;
    }

    var path = '';

    while (node) {
        var name = node.localName;
        var parent = node.parentNode;

        if (!parent) {
            path = name + ' > ' + path;
            continue;
        }

        if (node.getAttribute('id')) {
            path = '#' + node.getAttribute('id') + ' > ' + path;
            break;
        }

        var sameTagSiblings = [];
        var children = parent.childNodes;
        children = Array.prototype.slice.call(children);

        children.forEach(function(child) {
            if (child.localName == name) {
                sameTagSiblings.push(child);
            }
        });

        // if there are more than one children of that type use nth-of-type

        if (sameTagSiblings.length > 1) {
            var index = sameTagSiblings.indexOf(node);
            name += ':nth-of-type(' + (index + 1) + ')';
        }

        if (path) {
            path = name + ' > ' + path;
        } else {
            path = name;
        }

        node = parent;
    }

    return path;
}

So if you want to click on an element and get the unique selector just add:

window.addEventListener('click', function(event) {
    var ele = document.elementFromPoint(event.x, event.y);
    alert(getSelector(ele));
});

Upvotes: 3

Kenneth
Kenneth

Reputation: 28737

I suppose you mean a CSS selector. If so, it can be selected through multiple methods. If it has an id you can simply get the id from the element:

var selector = "#" + target.id;

Upvotes: -1

Related Questions