The structure is as follows

<div id="1" data-level="0">Комментарий</div> <div id="3" style="padding-left:20px" data-level="1">Ответ</div> <div id="4" style="padding-left:40px" data-level="2">Ответ на ответ</div> <div id="5" style="padding-left:40px" data-level="2">Ответ на ответ</div> <div id="7" style="padding-left:60px" data-level="3">Ответ на ответ на ответ</div> <div id="8" style="padding-left:60px" data-level="3">Ответ на ответ на ответ</div> <div id="6" style="padding-left:40px" data-level="2">Ответ на ответ</div> <div id="2" data-level="0">Комментарий</div> 

How to find in this structure, let's say that the id = '8' element has its parent element div with id = '5'.

Attempts to solve the problem:

 $('div[data-level]').each(function(){ var t = $(this), level = t.attr('data-level'), parent = $('div[data-level="'+(level-1)+'"]').attr('id'); //parent = $('div[data-level="'+(level-1)+'"]').prev().attr('id'); //parent = $(this).('div[data-level="'+(level-1)+'"]').prev().attr('id'); //parent = t.prev('div').attr('id'); if ( level > '0' ) { t.attr( "data-parent", parent ); t.html( 'Рельный ID:'+ t.attr('id') + ' Родительский:'+ parent ); } }); 

http://codepen.io/anon/pen/KdwYYP

  • Как в этой структуре найти допустим, что у элемента id='8' родительский элемент это div с id='5'. - ONET is not a parent in your example - dizballanze
  • This is the first one since the date-leveled one less, apparently so - splash58
  • by code yes, but in fact it is - Victor Onhodoev
  • ^ five points :) - splash58

1 answer 1

 $(document).on('click', "div", function() { var $this = $(this); var $dest = $this.prevAll("[data-level='" + ($this.data('level')-1) + "']").first(); if ($dest.length) { $dest.css('background', "red"); setTimeout(function() { $dest.css('background', ""); }, 1000); } }); 
 div { transition: all 3s linear; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="1" data-level="0">Комментарий</div> <div id="3" style="padding-left:20px" data-level="1">Ответ</div> <div id="4" style="padding-left:40px" data-level="2">Ответ на ответ</div> <div id="5" style="padding-left:40px" data-level="2">Ответ на ответ</div> <div id="7" style="padding-left:60px" data-level="3">Ответ на ответ на ответ</div> <div id="8" style="padding-left:60px" data-level="3">Ответ на ответ на ответ</div> <div id="6" style="padding-left:40px" data-level="2">Ответ на ответ</div> <div id="2" data-level="0">Комментарий</div> 

  • so, pozhe, he is not the parent in the sense of the structure of html - splash58
  • @ splash58, yes, I understand. I will correct now. My markup formatting knocked me down. - Qwertiy
  • @Viktor Onhodoy, corrected. - Qwertiy
  • @ splash58, corrected. - Qwertiy
  • Thank you very much !) - Victor Onkhodoev