使用 JavaScript 获取下一个/上一个元素? [英] Get next / previous element using JavaScript?

查看:43
本文介绍了使用 JavaScript 获取下一个/上一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 JavaScript 获取 HTML 中的下一个元素?

假设我有三个

并且我在 JavaScript 代码中得到一个引用,我想知道下一个

和这是以前的.

解决方案

在纯 javascript 中,我的想法是您首先必须将它们整理到一个集合中.

var divs = document.getElementsByTagName("div");//divs 现在包含页面上的每个 div 元素var selectionDiv = document.getElementById("MySecondDiv");

所以基本上用 selectionDiv 遍历集合以找到它的索引,然后显然 -1 = 前一个 +1 = 下一个在边界内

for(var i = 0; i 

请注意,正如我所说,需要额外的逻辑来检查您是否在范围内,即您不在集合的末尾或开头.

这也意味着假设您有一个嵌套有子 div 的 div.下一个 div 不是兄弟姐妹而是孩子,所以如果你只想要与目标 div 处于同一级别的兄弟姐妹,那么肯定使用 nextSibling 检查 tagName 属性.

How do I get the next element in HTML using JavaScript?

Suppose I have three <div>s and I get a reference to one in JavaScript code, I want to get which is the next <div> and which is the previous.

解决方案

Well in pure javascript my thinking is that you would first have to collate them inside a collection.

var divs = document.getElementsByTagName("div");
//divs now contain each and every div element on the page
var selectionDiv = document.getElementById("MySecondDiv");

So basically with selectionDiv iterate through the collection to find its index, and then obviously -1 = previous +1 = next within bounds

for(var i = 0; i < divs.length;i++)
{
   if(divs[i] == selectionDiv)
   {
     var previous = divs[i - 1];
     var next = divs[i + 1];
   }
}

Please be aware though as I say that extra logic would be required to check that you are within the bounds i.e. you are not at the end or start of the collection.

This also will mean that say you have a div which has a child div nested. The next div would not be a sibling but a child, So if you only want siblings on the same level as the target div then definately use nextSibling checking the tagName property.

这篇关于使用 JavaScript 获取下一个/上一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆