Sto creando una funzione per il mio sito in cui imposto un attributo di dati che contiene il numero nth-child di quell'elemento.Ottieni il numero nth-child di un elemento in puro JavaScript
mio markup HTML:
<html>
<body>
<section class="hardware">some text, nth-child is one</section>
<section class="hardware">some text, nth-child is two</section>
<section class="hardware">some text, nth-child is three</section>
<section class="hardware">some text, nth-child is four</section>
<section class="hardware">some text, nth-child is five</section>
</body>
</html>
mio JavaScript finora:
var selector = document.getElementsByClassName('hardware');
for(var i = 0; i <= selector.length; i++) {
var index = selector[i] //get the nth-child number here
selector[i].dataset.number = index;
}
Come posso ottenere il numero ennesima-figlio di un elemento con puro JavaScript (non jQuery), è presente anche possibile in JavaScript?
che è puro javascript no? – bitoiu
@bitoiu Sì, lo è, ma come posso ottenere il numero n-figlio? –
Se è possibile con jQuery, è anche possibile senza. Ricorda, jQuery è solo un insieme di funzioni JS. Semplifica le cose, non aggiunge funzionalità extra. – Darkwater