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

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

问题描述

如何使用javascript获取html中的下一个元素?
假设我有三个 div s,我得到一个js代码中的一个引用,我想得到哪个是下一个div,这是前一个。 / p>

How do I get the next element in html using javascript? Suppose I have three divs and I get a reference to one in js code, I want to get which is the next div and which is the previous.

推荐答案

在纯JavaScript中,我的想法是你首先必须将它们整理在一个集合中。

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");



< 1 =边界内的下一个

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.

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

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天全站免登陆