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?

有帮助吗?

解决方案

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

其他提示

You can try:

Array.prototype.forEach.call(
  document.getElementsById('someId').children,
  function (it) {
    it.classList.add('some-class');
  }
);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top