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:
$('.text'). Prev('.xpto');
– bfavaretto
The target of this command is the rect of the . foo ? class I’m trying to access the rect of class . Child
– Gabriel Lopes