0

I am letting user to take screenshot on div user clicking on from url, but how can I get css selector Ex.(#clients > div > div > div:nth-child(1)) to capture the screenshot. chrome copy selector


using jquery how can I achieve that, please help me with that.

Santosh Dangare
  • 685
  • 1
  • 4
  • 15
  • It's not clear to me. Do you want the user to get a selector when he clicks on a div ? Do you want to copy the HTML code of an element when the user provides a selector ? Or is it something else ? – Tom Feb 11 '22 at 13:21
  • @Tom , No, I have user's website inside iframe, so when user clicks on any div or section i want css selector of that div so will take screenshot of that div using [urlbox.io] service but that service need target selector to capture it – Santosh Dangare Feb 11 '22 at 13:28
  • how about? `$(document).on("click",".col-lg-2",function(){ var gotClickedElement = $(this).html(); });` I am not sure wether this works with iframe – stillKonfuzed Feb 11 '22 at 13:31
  • @stillKonfuzed from this I will get only html content but I need css selector when user click on any of the div – Santosh Dangare Feb 11 '22 at 13:34
  • 1
    oh you mean the classname? you can do `$(this).css();` for css or `$(this).prop('class');` for classnames or if conditional then `$(this).hasClass('some-classname');` – stillKonfuzed Feb 11 '22 at 13:34
  • Does this answer your question? [Getting a jQuery selector for an element](https://stackoverflow.com/questions/2068272/getting-a-jquery-selector-for-an-element) – Tom Feb 11 '22 at 13:40
  • @stillKonfuzed see this https://imgur.com/a/tCFDyJJ ,I want targetSelector like this section:nth-child(2) , not only classname or id or element – Santosh Dangare Feb 11 '22 at 13:43
  • @Tom yeah some what similar but I am not able to use that fucntion as it is giving unexpected token 'class' , how can use it like normal fucntion like ```$(document).on("click","#iframe",function(e){ getPath(e.target); //or $(this) });``` – Santosh Dangare Feb 11 '22 at 13:52

1 Answers1

0

I got the answer fot this using library which generates CSS selectors from DOM nodes jhartikainen/dompath and it easy to implement.
Just add dompath.js script into your file.
USAGE :

e.target.contentDocument.body.addEventListener('click', e => {
    targetSelector= '';

    //call function, pass any element:
    var csspath = dompath(e.target);

    //get CSS selector:
    targetSelector = csspath.toCSS();
    console.log(targetSelector);
    //#about > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > ul:nth-child(2) > li:nth-child(1)
});
Santosh Dangare
  • 685
  • 1
  • 4
  • 15