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

Asked

Viewed 506 times

1

Hello,

I’m trying to make a function that by clicking on an element I can either catch the tree(all parents) of the element (up to the body or a specific tag), or take something similar to the "Copy -> Copy Selector" of Devtools.

inserir a descrição da imagem aqui

For example when I click on b return me something like div > nav > h3 > b.

Clicking on the label return div > label.

Clicking on the h3 return div > nav > h3.

You can include the body if you want... If you need to insert an id in an element to know where to stop is a viable solution too.

Thank you in advance!

Edit

Improving doubt...

Let’s assume I have an HTML structure inside a div.

For example:

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

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

  • div
    • Nav
      • label
    • label

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

So when I click I would need to take the parent 'cause then I’d just use $(aqui) being aqui = #stack-ex > div > nav > label.

The click was just something to illustrate for you to help me with a practical example, I’m not necessarily going to click and call the function.

  • Renan, you only need the name of the tags ? or the HTML object itself?

  • Basically the same string.

  • I really couldn’t quite understand the purpose. I even apologized, but I didn’t really understand. I think it would be interesting to talk in a chat so you can explain this and what the goal is, because I’m finding it strange to take the whole tree of the element. I believe that I should have a better and simpler solution. I stand by.

  • Hello, we can chat yes in a chat, how can we do this?

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
});

1

You can create a click event for all elements of body and treat the click on the clicked element, searching for their ancestors. At the end 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>
<body id="corpo">
<div>
   div
   <nav>
      nav
      <h3>
         H3
         <b>
            b
         </b>
      </h3>
   </nav>
   <label>
      label
   </label>
</div>
</body>

One comment on the Bubbling:

As one element is within 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 fired in the clicked element and in all its ancestors, but what we want is for the event to listen only to the clicked element. The .stopPropagation() serves precisely for this, avoid that the event is also fired by the ancestors of the element clicked. Has a good topic here that deals with the subject.

  • Thanks for the explanation, it really helped me!

  • Let’s talk around here

  • face, I still do not understand it right. It takes an example of the structure of HTML and what you want of result.

  • I’ll explain the problem at first. I’m taking the HTML inside a DIV and I’m showing it as list So something like: <div> <Nav> <label> Text </label> </Nav> <label> Text 2 </label> </div> It is listed as: -div > Nav * label > label I wanted to click on an item from a list (which refers to the HTML above), to return me its tree. To use later in Jquery as selector $(here). And so be able to reference the element later.

  • Poxa, the structure of the list was in the same line here in the comments. But I hope you understand.

  • So but I need those elements listed elsewhere and their reference.. To change some attributes of it. Display, color, etc... And it has to be dynamic to any page.

  • If you can set an example, it might help

  • I will do the following, I will reply here outside the comments, because you can use HTML and structure the question better. I will answer right here.

  • I answered down here... rs

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.