Pregunta

How do you select all direct children of an element, not matter what type of element, in JavaScript?

Here's how you do it in JQuery:

$("#someID > *").addClass("some-class");

What is the JavaScript equivalent?

¿Fue útil?

Solución

document.querySelectorAll() pretty much works the same way as the jQuery selector for most cases (not all, though!). While traversing the resulting NodeList, classList property to set your respective class.

var els = document.querySelectorAll( '#someID > *' );
for( var i=els.length; i--; ) {
  els[i].classList.add( 'some-class' );
}

Otros consejos

You can try:

Array.prototype.forEach.call(
  document.getElementsById('someId').children,
  function (it) {
    it.classList.add('some-class');
  }
);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top