문제

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