I'm trying to select every first item of a serie of multiple blocks but I can't figure out how to do this :(
Here is an exemple of what I've tried :
let everyItems = Array.from(document.querySelectorAll('.block .item'));
let firstItems = Array.from(everyItems[0]);
document.getElementById('every1stItem').innerText = firstItems.innerText;
<div calss="block"><b>First block</b>
<div >Item 1.1</div>
<div >Item 1.2</div>
<div >Item 1.3</div>
<div >Item 1.4</div>
</div>
<div calss="block"><b>Second block</b>
<div >Item 2.1</div>
<div >Item 2.2</div>
<div >Item 2.3</div>
<div >Item 2.4</div>
</div>
<div calss="block"><b>Third block</b>
<div >Item 3.1</div>
<div >Item 3.2</div>
<sdivan >Item 3.3</div>
<div >Item 3.4</div>
</div>
<div>
<b>The first item of every block is :</b>
<div id="every1stItem"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Thank you for helping me out !
CodePudding user response:
You can do something like this
let everyItems = Array.from(document.querySelectorAll('.block'));
let firstItems = everyItems.map(i => i.children[1].innerText).join(', ')
document.getElementById('every1stItem').innerText = firstItems;
<div ><b>First block</b>
<div >Item 1.1</div>
<div >Item 1.2</div>
<div >Item 1.3</div>
<div >Item 1.4</div>
</div>
<div ><b>Second block</b>
<div >Item 2.1</div>
<div >Item 2.2</div>
<div >Item 2.3</div>
<div >Item 2.4</div>
</div>
<div ><b>Third block</b>
<div >Item 3.1</div>
<div >Item 3.2</div>
<div >Item 3.3</div>
<div >Item 3.4</div>
</div>
<div>
<b>The first item of every block is :</b>
<div id="every1stItem"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CodePudding user response:
using :nth-child(n)
selector
let everyItems = $('.item:nth-child(2)');
$('#every1stItem').html(everyItems)
<div>
<b>The first item of every block is :</b>
<div id="every1stItem"></div>
</div>
<hr>
<div ><b>First block</b>
<div >Item 1.1</div>
<div >Item 1.2</div>
<div >Item 1.3</div>
<div >Item 1.4</div>
</div>
<div ><b>Second block</b>
<div >Item 2.1</div>
<div >Item 2.2</div>
<div >Item 2.3</div>
<div >Item 2.4</div>
</div>
<div ><b>Third block</b>
<div >Item 3.1</div>
<div >Item 3.2</div>
<div >Item 3.3</div>
<div >Item 3.4</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CodePudding user response:
document.queryselector(".className")
returns the first element with the class className