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

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

问题描述



假设我有三个< div> s,并且我在JavaScript代码中获得了一个引用,我想要得到哪个是下一个< div> ,哪个是前一个。

解决方案

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

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

所以基本上用selectionDiv遍历集合来找到它的索引,然后显然-1 = previous + 1 =下一个范围内

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






$ b

请注意,虽然我说额外的逻辑会被要求检查你是否在界限内,即你不在收集的最后或开始。



这也意味着你说有一个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天全站免登陆