Вы можете использовать свойство children
для доступа к дочерним элементам данного узла:
Свойство
blockquote>ParentNode
g2]children
- свойство только для чтения, которое возвращает живой HTMLCollection , который содержит все дочерние элементы узла, на который он был вызван.
function myFunction() { var divv = document.getElementById("divv"); var myCollection = divv.children; var len = myCollection.length; var i; for (i = 0; i < len; i++) { myCollection[i].style.color = "red"; } }
JavaScript HTML DOM
Hello World!
Hello Norway!
Click the button to change the color of all p elements.
Другой способ сделать ES6 будет распространять дочерние узлы в массив и прокручивать их с помощью
.forEach
:
const myFunction = () => { [...document.querySelector('#divv').children].forEach(child => { child.style.color = 'red'; }); }
I am a childI am a grand childВ качестве альтернативы вы можете использовать
.forEach
непосредственно из классаNodeList
, но предыдущий метод дает вам больше свободы для работы с методом Array, таким как.reduce
,.map
и т. д. ...
const myFunction = () => { document.querySelectorAll('#divv > *').forEach(child => { child.style.color = 'red'; }); }
I am a childI am a grand child
Попробуйте:
HTML
<div class="container">
<div class="item">
<div class="item__image"><img src="https://dummyimage.com/300x300/000/fff" /></div>
<div class="item__content">
<div class="item__title"><h4>Title</h4></div>
<div class="item__body"><p>Paragraphs of various lenthParagraphs of various lengthParagraphs of various length</p></div>
</div>
<div class="item__options">
<button class="btn btn-default">CTA</button>
</div>
</div>
<div class="item">
<div class="item__image"><img src="https://dummyimage.com/300x300/000/fff" /></div>
<div class="item__content">
<div class="item__title"><h4>Title</h4></div>
<div class="item__body"><p>Paragraphs of various lenthParagraphs of various lengthParagraphs of various length</p></div>
</div>
<div class="item__options">
<button class="btn btn-default">CTA</button>
</div>
</div>
<div class="item">
<div class="item__image"><img src="https://dummyimage.com/300x300/000/fff" /></div>
<div class="item__content">
<div class="item__title"><h4>Title</h4></div>
<div class="item__body"><p>Paragraphs of various lenthParagraphs of various lengthParagraphs of various length</p></div>
</div>
<div class="item__options">
<button class="btn btn-default">CTA</button>
</div>
</div>
</div>
CSS
.container {
display: flex;
}
.item {
display: flex;
flex-flow: column;
}
.item:not(last-child) {
margin-right: 10px;
}
.item__image {
}
.item__content {
flex: 2 ;
}
.item__options {
text-align: center;
height: 100px;
}
просмотреть вывод здесь: https://jsfiddle.net/2467mgn5/ 2 /