Accessing an element within the same element hierarchy

Asked

Viewed 97 times

1

Next, I have this situation:

<html>
  <g class="children">
     <g>
        <rect class="child" data-id="xpto"></rect>
     </g>
     <rect class="xpto"></rect>
     <text class="texto">
        <tspan></tspan>
     </text>
   </g>
</html>  

I need to exit the "text" element and access the "data-id" attribute of the "rect" that is inside the "g" element. Any idea how I can do this?

  • $('.text'). Prev('.xpto');

  • The target of this command is the rect of the . foo ? class I’m trying to access the rect of class . Child

2 answers

1

You can use the .Parent to find the parent of the element text (in this case would return the first g of the tree, which contains the class="children" and from it search for the rect referring to the parent, after finding the element in the tree you can use the date to catch the data-id element. Follow an example code

var el = $( ".texto" ).parent();
var id = el.find('g rect.child').data('id');
console.log(id);

//Ou pra simplificar
var data_id = $(".texto").parent().find('g rect.child').data('id');
console.log(data_id);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
  <g class="children">
     <g>
        <rect class="child" data-id="xpto"></rect>
     </g>
     <rect class="xpto"></rect>
     <text class="texto">
        <tspan></tspan>
     </text>
   </g>
</html>

1


I think the simplest way to do that is to use the prev twice to reach the desired element.

Then just use the children to access the rect and read the attribute data-id.

const $el = $('.texto')

// Acessar o `<g>`, voltando dois elementos:
const $g = $el.prev().prev()

// Acessar o `<rect>` dentro do `<g>`:
const $rect = $g.children('rect')

// Capturar os atributos desejados:
const dataId = $rect.attr('data-id')

console.log(dataId)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<html>
  <g class="children">
     <g>
        <rect class="child" data-id="xpto"></rect>
     </g>
     <rect class="xpto"></rect>
     <text class="texto">
        <tspan></tspan>
     </text>
   </g>
</html>

Doing using only one line of code:

const id = $('.texto').prev().prev().children('rect').attr('data-id')
console.log(id)

However, jQuery gives us several ways to achieve the same result. The above solution includes one of several ways to do it. Another of them would be using the prevUntil, parent, etc..

Reference:

Browser other questions tagged

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