在querySelector中:如何获取第一个元素并获取最后一个元素?在dom中使用了什么遍历顺序?

cc *_*ung 56 javascript html5 dom

在div中,具有属性的元素(不一定是第2代)move_id.

首先,想要最直接的方法来获取集合的第一个和最后一个元素

尝试获得第一个和最后一个:

var first = div.querySelector('[move_id]:first');
var last  = div.querySelector('[move_id]:last');
Run Code Online (Sandbox Code Playgroud)

这个炸弹是因为:第一个和最后一个是我的一厢情愿(?)

不能使用Array方法,querySelectorAll因为NodeList不是数组:

var first = (div.querySelectorAll('[move_id]'))[0];
var last  = (div.querySelectorAll('[move_id'])).pop();
Run Code Online (Sandbox Code Playgroud)

这个炸弹因为NodeList没有方法pop()

(是的,可以在NodeList之上使用Array方法:

var first = div.querySelector('[move_id]');
var last = Array.prototype.pop.call(div.querySelectorAll('[move_id']));
Run Code Online (Sandbox Code Playgroud)

这是有效的,也是我现在正在使用的,但我认为必须有一些更直接的东西,我只是缺少了)

其次,需要根据http://en.wikipedia.org/wiki/Tree_traversal验证元素是按照pre-oder深度优先遍历列出的

Anu*_*rag 72

要访问第一个和最后一个元素,请尝试.

var nodes = div.querySelectorAll('[move_id]');
var first = nodes[0];
var last = nodes[nodes.length- 1];
Run Code Online (Sandbox Code Playgroud)

为了增强稳定性,请添加索引检查.

是的,节点的顺序是预先深度优先的.DOM的document order定义为,

存在在文档中的所有节点上定义的排序,文档顺序,其对应于在扩展一般实体之后在文档的XML表示中出现每个节点的XML表示的第一字符的顺序.因此,文档元素节点将是第一个节点.元素节点出现在他们的孩子之前 因此,文档顺序命令元素节点按照它们在XML中的开始标记的出现顺序(在实体扩展之后).元素的属性节点出现在元素之后和子元素之前.属性节点的相对顺序取决于实现.


Gui*_*ssé 67

:last 不是css规范的一部分,这是jQuery特有的.

你应该找 last-child

var first = div.querySelector('[move_id]:first-child');
var last  = div.querySelector('[move_id]:last-child');
Run Code Online (Sandbox Code Playgroud)

  • `:last-child`和`:first-child`与父元素相关,而不是与列表相关!这意味着可能有几个第一胎和几个最后一个孩子,这不是所要求的.见这里:http://jsfiddle.net/r61tcvc3/ (26认同)
  • :last和:last-child不一样.它可以给你相同的结果,但它取决于HTML结构. (3认同)

vsy*_*ync 25

在此处添加一个解决方案的答案(与其他建议的有点不同):

使用:last-of-type选择器获取某个特定标签名称的最后一个元素。

数组方法at()与 结合使用也很有帮助querySelectorAll,但它需要破坏结果,以获得“真正的”数组,因为querySelectorAll没有at可用的方法(太悲伤了......)

console.log(
  ":last-of-type:",
  document.querySelector('mark:last-of-type') // <---- 
)

console.log(
  ":last-child:",
  document.querySelector('mark:last-child')
)

console.log(
  "querySelectorAll + at:",
  [...document.querySelectorAll('mark')].at(-1)
)
Run Code Online (Sandbox Code Playgroud)
<p>
this is <mark>highlighted</mark> and this is <mark>is also</mark> but <strong>not this</strong>.
</p>
Run Code Online (Sandbox Code Playgroud)


g.b*_*eze 6

获取最后一个输入元素的示例:

document.querySelector(".groups-container >div:last-child input")

  • 事实上并非如此。该答案仅从“DIV:last-child”获取“INPUT:first-child”。请参阅此处:https://jsfiddle.net/nqtpk5gd/1/ (2认同)

小智 5

let first = div.querySelector('[move_id]');
let last  = Array.from(div.querySelectorAll('[move_id]')).pop();
Run Code Online (Sandbox Code Playgroud)