Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

You can try:

Array.prototype.forEach.call(
  document.getElementsById('someId').children,
  function (it) {
    it.classList.add('some-class');
  }
);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top