使用给定节点(javascript)中的类名查找下一个节点?

时间:2017-05-24 07:12:26

标签: javascript

例如

    <div class="descendants" style="width:500px;">div (current element) 
      <p>p (child)
        <span class="testclass">span (grandchild)</span>     
      </p>
      <p>p (child)
        <span>span (grandchild)</span>
      </p> 
    </div>
    <p class="testclass">This is paragraph</p>
   <div class="descendants" style="width:500px;">div (current element) 
      <p>p (child)
        <span>span (grandchild)</span>     
      </p>
      <p>p (child)
        <span>span (grandchild)</span>
      </p> 
    </div>

这是示例代码。我有一个节点<span class="testclass">span (grandchild)</span>我需要使用javascript找到具有相同类名testclass的下一个节点。

1 个答案:

答案 0 :(得分:0)

试试这个$(this).closest('.descendants').next('.testclass').text()。您应该使用closest()定位最后一位家长。然后使用next()申请。其目标与下一个p.testclass

&#13;
&#13;
$('.testclass').eq(0).click(function(){
console.log($(this).closest('.descendants').next('.testclass').text())

})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="descendants" style="width:500px;">div (current element)
  <p>p (child)
    <span class="testclass">span (grandchild)</span>
  </p>
  <p>p (child)
    <span>span (grandchild)</span>
  </p>
</div>
<p class="testclass">This is paragraph</p>
<div class="descendants" style="width:500px;">div (current element)
  <p>p (child)
    <span>span (grandchild)</span>
  </p>
  <p>p (child)
    <span>span (grandchild)</span>
  </p>
</div>
&#13;
&#13;
&#13;