JavaScript 如何获取子节点索引

JavaScript 如何获取子节点索引

任务是获取子元素在其他子元素中的索引。下面是几种讨论过的技巧。

方法1

  • 选择父元素的子元素。
  • 通过 .parentNode 属性选择父元素。
  • 使用 Array.prototype.indexOf.call(Children_of_parent, current_child) 来获取索引。

示例1: 使用上述方法的示例。

<style> 
    .parent { 
        background: green; 
        color: white; 
    } 
      
    #child1 { 
        background: blue; 
        color: white; 
        margin: 10px; 
    } 
      
    #child2 { 
        background: red; 
        color: white; 
        margin: 10px; 
    } 
</style> 
<h1 style="color:green;"> 
    GeeksforGeeks 
</h1> 
<p id="GFG_UP"> 
</p> 
<div class="parent" id="parent"> 
    Parent 
    <div id="child1"> 
        Child1 
    </div> 
  
    <div id="child2"> 
        Child2 
    </div> 
</div> 
<br> 
<button onclick="GFG_Fun()"> 
    click here 
</button> 
  
<p id="GFG_DOWN"> 
</p> 
<script> 
    var up = document.getElementById('GFG_UP'); 
    var down = document.getElementById('GFG_DOWN'); 
    up.innerHTML = 
    "Click on the button get the index of child element."; 
      
    function GFG_Fun() { 
        var child = document.getElementById('child2'); 
        var parent = child.parentNode; 
        down.innerHTML = 
        "The index of element with id = 'child2' is = " 
        + Array.prototype.indexOf.call(parent.children, child); 
    } 
</script>
HTML

输出:

JavaScript 如何获取子节点索引

方法2

  • 选择父元素的子元素。
  • 首先选择父元素,然后选择父元素的所有子元素。
  • 创建一个子元素的数组,并使用 indexOf()方法 来获取索引。

示例2: 此示例使用了上述讨论的方法。

<style> 
    .parent { 
        background: green; 
        color: white; 
    } 
      
    #child1 { 
        background: blue; 
        color: white; 
        margin: 10px; 
    } 
      
    #child2 { 
        background: red; 
        color: white; 
        margin: 10px; 
    } 
</style> 
  
<h1 style="color:green;"> 
    GeeksforGeeks 
</h1> 
<p id="GFG_UP"> 
</p> 
<div class="parent" id="parent"> 
    Parent 
    <div id="child1"> 
        Child1 
    </div> 
  
    <div id="child2"> 
        Child2 
    </div> 
</div> 
<br> 
<button onclick="GFG_Fun()"> 
    click here 
</button> 
  
<p id="GFG_DOWN"> 
</p> 
<script> 
    var up = document.getElementById('GFG_UP'); 
    var down = document.getElementById('GFG_DOWN'); 
    up.innerHTML = 
    "Click on the button get the index of child element."; 
      
    function GFG_Fun() { 
        var child = document.getElementById('child2'); 
        down.innerHTML = "The index of element with id = 'child2' is = " 
        + Array.from(child.parentNode.children).indexOf(child); 
    } 
</script>
HTML

输出:

JavaScript 如何获取子节点索引

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册