JS - How to get the selector of the Element or its tree?

1

Hello,

I'm trying to do a function that when I click on an element I can get either the tree (all parents) of the element (up to the body or a specific tag), or get something similar to "Copy -> Copy Selector "from DevTools.

ForexamplewhenIclickonbIreturnsomethinglikediv>nav>h3>b.

Byclickingonlabelreturndiv>label.

Byclickingonh3returndiv>nav>h3.

Youcanincludethebodyifyouwant...Ifyouneedtoinsertanidintoanelementtoknowwheretostopisaviablesolutionaswell.

Thankyouinadvance!

Edit

Improvingthedoubt...

Let'ssupposeIhaveanHTMLstructureinsideadiv.

Asforexample:

<divid="stack-ex">
     <div>
         <nav>
              <label>Teste</label>
         </nav>
         <label>Texto 2</label>
     </div>
</div>

I need to list the content of #stack-ex something like this:

  • div
    • nav
      • label
    • label

So the structure of <li> is a reference to the contents of #stack-ex , I would later need along with the list to have the selector of the element that the list item references. Then I'll put something like a button to change color, or other cases.

So by clicking, you would need to get the parent of it because then you would only use $(aqui) being aqui = #stack-ex > div > nav > label .

The click was just something to exemplify for you to help me with a practical example, I will not necessarily click and call the function.

    
asked by anonymous 30.08.2018 / 16:10

2 answers

1

With jQuery you can return the tree like this.

$('.evento').on('click', function () {
  $(this).parentsUntil('div.root');
  // ele não retornará o elemento atual clicado
  // então você pode pegar ele com o $(this) mesmo
});
    
30.08.2018 / 18:04
1

You can create a click event for all elements of body and treat the click on the clicked element by searching for your ancestors. At the end it will return a string in the format you requested (other explanations in the code):

$("body *").click(function(e){
   e.stopPropagation();          // evita o bubbling
   var ateh = "#corpo";          // seletor que define até onde irá procurar o ancestral
                                 // pode ser um id, class, tag ou outro seletor válido
   var prev = $(this)            // pega o elemento clicado
   .parentsUntil(ateh)           // pega os ancestrais até o primeiro filho definido na variável ateh
   .addBack();                   // adiciona o elemento clicado (jQuery v1.8 ou maior)
//   .andSelf();                 // adiciona o elemento clicado (jQuery v1.7 ou menor)
   var tags = prev.get()         // pega os elementos do nodelist
   .map(function(a){             // e converte em uma array com os objetos HTML
      return a.tagName           // retorna os nomes das tags do objetos HTML
   })
   .join(" > ")                  // converte em string separando-os por " > "
   .toLowerCase();               // converte tudo em minúsculas
   var pais = ateh               // monta a string final incluindo o ancestral definido
   + " > "                       // na variável ateh que não foi incluído no .parentsUntil()
   + tags;

   console.clear();              // limpa o console
   console.log(pais);            // imprime no console
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><bodyid="corpo">
<div>
   div
   <nav>
      nav
      <h3>
         H3
         <b>
            b
         </b>
      </h3>
   </nav>
   <label>
      label
   </label>
</div>
</body>

A note about bubbling :

As one element is inside another (it is a direct descendant or not), if you click on it you will be clicking on your parents as well. That is, the event will be triggered on the clicked element and all its ancestors, but we want the event to listen only to the clicked element. The .stopPropagation() is exactly for this, to prevent that the event is also fired by the ancestors of the clicked element. You have a good topic here that deals with the subject.

    
30.08.2018 / 18:34