Reputation: 83
is there a possibility to appeal (without jquery) with just pure javascript to nth-child() and nth-last-of-type()? I want to largely avoid the use of jquery.
Upvotes: 4
Views: 8317
Reputation: 2653
Use CSS :last-child Selector
The :last-child selector matches every element that is the last child of its parent.
For example
var elements = document.querySelectorAll('div:last-child');
console.log(elements);
// example output
// NodeList(32)[div.container, div, div, ...]
ref: https://www.w3schools.com/cssref/sel_last-child.asp
Upvotes: 0
Reputation: 11
This should help. You can use this to get the element you desire by class name. You could also .getElementById if no class is present.
var x = document.getElementsByClassName("class-name")[index#];
See it work here: JSFiddle
Upvotes: 0
Reputation: 16777
Use document.querySelectorAll.
For example
var elements = document.querySelectorAll('div:nth-child(5)');
Summary
Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.
Syntax
elementList = document.querySelectorAll(selectors);
where
elementList is a non-live NodeList of element objects.
selectors is a string containing one or more CSS selectors separated by commas.
The returned NodeList will contain all the elements in the document that are matched by any of the specified selectors. If the selectors string contains a CSS pseudo-element, the returned elementList will be empty.
Upvotes: 4