Home  >  Q&A  >  body text

javascript - How to get the number of the parent element of a future element among all the same elements on the page?

The entire code is dynamically added to the page through js. When b changes, how to get the position (position) of a among all a's on the page?

<p class="a">
    <p class="b"></p>
</p>
淡淡烟草味淡淡烟草味2662 days ago769

reply all(3)I'll reply

  • 漂亮男人

    漂亮男人2017-07-05 10:55:27

    I don’t quite understand what it means

    If the class name of a is unchanged, use jQuery directly

    $(".a").index(this.parent())

    where this is the changed b

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-07-05 10:55:27

    [...document.querySelector('.b').parentNode.parentNode.children].indexOf(document.querySelector('.b').parentNode)

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 10:55:27

    Since it is added dynamically, why not give it an identifier before adding it to the dom? For example:

    <p class="a" index="1">
        <p class="b"></p>
    </p>
    <p class="a" index="2">
        <p class="b"></p>
    </p>
    ...

    In this way, when b changes, just get the parent’s index attribute directly

    reply
    0
  • Cancelreply