Pergunta

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?

Foi útil?

Solução

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' );
}

Outras dicas

You can try:

Array.prototype.forEach.call(
  document.getElementsById('someId').children,
  function (it) {
    it.classList.add('some-class');
  }
);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top