最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery get unique css selector on rightclick menu item or click a dom element - Stack Overflow

programmeradmin0浏览0评论

I am trying to alert the correct css selector and xpath on right click on a dom element. I can show a menu on right click but I'm blocked getting the css selector and xpath value. Input for the code will be any website source code (right click on site, view source) or sample html code which has some classnames. I have a reference to pull unique css selector here

Any pointers on how to get unique css selector and xpath on right click on any dom element?

My Fiddle is here

<h2>Copy paste source code</h2>
<textarea id="txtSrcCode"></textarea>
<input type="button" value="Load Page" id="btnLoadPage" />
<div id="divToBindSrcCode">

</div>

<ul class='custom-menu'>
  <li data-action="first">First thing</li>
  <li data-action="second">Second thing</li>
  <li data-action="third">Third thing</li>
</ul>

Jquery code

$('#btnLoadPage').click(function() {
  $('#divToBindSrcCode').html($('#txtSrcCode').val()); // Laod dom on to the page
});

$(document).bind("contextmenu", function(event) {

  // Avoid the real one
  event.preventDefault();
  // Show contextmenu
  $(".custom-menu").finish().toggle(100).

  // In the right position (the mouse)
  css({
    top: event.pageY + "px",
    left: event.pageX + "px"
  });
});


// If the document is clicked somewhere
$(document).bind("mousedown", function(e) {
  // If the clicked element is not the menu
  if (!$(e.target).parents(".custom-menu").length > 0) {
    // Hide it
    $(".custom-menu").hide(100);
  }
});

// If the menu element is clicked
$(".custom-menu li").click(function() {
  var kk = $(this).val();
  // This is the triggered action name
  switch ($(this).attr("data-action")) {
    // A case for each action. Your actions here
    case "first":
      alert(kk);
      break;
    case "second":
      alert("second");
      break;
    case "third":
      alert("third");
      break;
  }

  // Hide it AFTER the action was triggered
  $(".custom-menu").hide(100);
});

I am trying to alert the correct css selector and xpath on right click on a dom element. I can show a menu on right click but I'm blocked getting the css selector and xpath value. Input for the code will be any website source code (right click on site, view source) or sample html code which has some classnames. I have a reference to pull unique css selector here

Any pointers on how to get unique css selector and xpath on right click on any dom element?

My Fiddle is here

<h2>Copy paste source code</h2>
<textarea id="txtSrcCode"></textarea>
<input type="button" value="Load Page" id="btnLoadPage" />
<div id="divToBindSrcCode">

</div>

<ul class='custom-menu'>
  <li data-action="first">First thing</li>
  <li data-action="second">Second thing</li>
  <li data-action="third">Third thing</li>
</ul>

Jquery code

$('#btnLoadPage').click(function() {
  $('#divToBindSrcCode').html($('#txtSrcCode').val()); // Laod dom on to the page
});

$(document).bind("contextmenu", function(event) {

  // Avoid the real one
  event.preventDefault();
  // Show contextmenu
  $(".custom-menu").finish().toggle(100).

  // In the right position (the mouse)
  css({
    top: event.pageY + "px",
    left: event.pageX + "px"
  });
});


// If the document is clicked somewhere
$(document).bind("mousedown", function(e) {
  // If the clicked element is not the menu
  if (!$(e.target).parents(".custom-menu").length > 0) {
    // Hide it
    $(".custom-menu").hide(100);
  }
});

// If the menu element is clicked
$(".custom-menu li").click(function() {
  var kk = $(this).val();
  // This is the triggered action name
  switch ($(this).attr("data-action")) {
    // A case for each action. Your actions here
    case "first":
      alert(kk);
      break;
    case "second":
      alert("second");
      break;
    case "third":
      alert("third");
      break;
  }

  // Hide it AFTER the action was triggered
  $(".custom-menu").hide(100);
});
Share Improve this question edited Jun 1, 2017 at 15:17 daphtdazz 8,1591 gold badge37 silver badges57 bronze badges asked May 29, 2017 at 5:45 KurkulaKurkula 6,78228 gold badges138 silver badges215 bronze badges 2
  • 1 Did you check out this answer? – 31piy Commented Jun 1, 2017 at 11:37
  • click and right click works differently with $(this) and pulling its parent elements for xpath or css selector. – Kurkula Commented Jun 3, 2017 at 21:48
Add a ment  | 

2 Answers 2

Reset to default 4 +50

Putting the answer of @jeka5555 together with a library such as css-selector-generator.js, and using MDN's xpath generator you can do this:

<html>
    <head>
        <script src="./css-selector-generator.js"></script>
        <script>
            function getXPathForElement(el, xml) {
                var xpath = '';
                var pos, tempitem2;

                while(el !== xml.documentElement) {
                    pos = 0;
                    tempitem2 = el;
                    while(tempitem2) {
                        if (tempitem2.nodeType === 1 && tempitem2.nodeName === el.nodeName) { // If it is ELEMENT_NODE of the same name
                            pos += 1;
                        }
                        tempitem2 = tempitem2.previousSibling;
                    }

                    xpath = "*[name()='"+el.nodeName+"' and namespace-uri()='"+(el.namespaceURI===null?'':el.namespaceURI)+"']["+pos+']'+'/'+xpath;

                    el = el.parentNode;
                }
                xpath = '/*'+"[name()='"+xml.documentElement.nodeName+"' and namespace-uri()='"+(el.namespaceURI===null?'':el.namespaceURI)+"']"+'/'+xpath;
                xpath = xpath.replace(/\/$/, '');
                return xpath;
            }
        </script>
        <script>
            function context(event) {
                event.preventDefault();
                console.log(event.target);
                var sel_gen = new CssSelectorGenerator();
                var sel = sel_gen.getSelector(event.target);
                var xpath = getXPathForElement(event.target, document);
                alert("sel: " + sel + "; xpath: " + xpath);
            }
        </script>
    </head>

    <body>
        <div class=myclass>
            <div>
                <p oncontextmenu="context(event)">Right click me</p>
                <p>Clicking me won't help</p>
            </div>
        </div>
    </body>
</html>

This particular case alerts:

sel: .myclass > div > :nth-child(1); xpath: /*[name()='HTML' and namespace-uri()='http://www.w3/1999/xhtml']/*[name()='BODY' and namespace-uri()='http://www.w3/1999/xhtml'][1]/*[name()='DIV' and namespace-uri()='http://www.w3/1999/xhtml'][1]/*[name()='DIV' and namespace-uri()='http://www.w3/1999/xhtml'][1]/*[name()='P' and namespace-uri()='http://www.w3/1999/xhtml'][1]

I would trust the library to get it right much more than I would trust myself!

And try this jsfiddle.

Also this jsfiddle modifies the Mozilla function to give a simpler xpath.

There are other libraries available for the css selector, see this answer to a similar question.

event.target - indicates the element by which you clicked

发布评论

评论列表(0)

  1. 暂无评论