Home>

I want to connect the parent ".parent_num" before my ".parent_num".

That means I want JS to make the changes commented out in the HTML below.

However, the change occurs only in ".childrens", and Mr. A cannot connect ".parent_num" of his parent Y family before his ".parent_num".

<li>
  <div>Y house
    <span>100</span>
    <span>0</span>
  </div>
  <ul>
    <li>
      <div>A (housekeeper)
        <span>101</span>
        <span>100</span>
      </div>
    </li>
    <li>
      <div>B (child of A)
        <span>102</span>
        <span>101</span>
        <!-I want parent_num to be "100-101" in JS->
      </div>
    </li>
    <li>
      <div>C (child of A)
        <span>103</span>
        <span>101</span>
        <!-I want parent_num to be "100-101" in JS->
      </div>
    </li>
    <li>
      <div>D (child of C)
        <span>104</span>
        <span>103</span>
        <!-I want to set parent_num to "100-101-103" in JS->
      </div>
    </li>
  </ul>
</li>


That's why I thought of jQuery like this, but it wasn't tiring and I couldn't do it.
Please let me know if you know how.

// Put all num in the array
var arr = [];
$(". num"). each (function () {
  arr.push ($(this) .text ());
});
// In every parent_num
$(". parent_num"). each (function () {
  // If it is the same value as your num, add "parent's parent_num" and "-" before your value.
  var myNum = $(this) .consest ('div'). find ('. num'). text ();
  var parentNum =
  if (arr == myNum) {
    $(this) .prepend (parentNum + '-');
  }
});
  • Answer # 1

    $('.childrens') .each (function () {
        var $_t = $(this);
        var f_num = $_t.prev (). find ('.num') .text ();
        $_t.find ('.parent_num') .each (function () {
            var p_num = $(this) .text ();
            if (f_num! = p_num) {
                $(this) .text (f_num + '-' + p_num);
            }
        });
    });

    Moving sample:https://jsfiddle.net/vzhjs3ad/


    Addition:

    In the first place, the structure of HTML and the structure of data are different.

    $('.num, .parent_num') .each (function () {
        var $_t = $(this);
        var c_name = $_t.hasClass ('num')? 'num': 'parent_num';
        $_t.attr ('data-' + c_name, $_t.text ());
    });
    $('.childrens') .each (function () {
        var $_t = $(this);
        var f_num = $_t.prev (). find ('.num') .text ();
        $_t.find ('.parent_num') .each (function () {
            var p_num = $(this) .attr ('data-parent_num');
            if (f_num == p_num) return;
            var parent_num = 'xyz';
            var res_num = [p_num];
            while (parent_num) {
                parent_num = $_t.find ('[data-num = "' + res_num [0] + '"]') .first (). next (). attr ('data-parent_num');
                res_num.unshift (parent_num);
            }
            $(this) .text (res_num.join ('-'));
        });
    });

    Moving sample:https://jsfiddle.net/vzhjs3ad/1/