node_man
node_man

Reputation: 1449

How to display only a few cards at a time using core javascript?

So, I already have a working code for this requirement in jquery which displays the specified number of cards/divs. For some reason, I have been asked to use pure javascript and I'm not able to achieve it in core javascript.

Here is my fully working jquery code:

size_timelinediv = $("#timeline t").length;
console.log(size_timelinediv)//prints 5
var x = 3; //number of cards to be displayed
$("#timeline t:lt("+x+")").show(); //displays the first 3 <t> tags only
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="timeline" id="timeline" >
<t style="display:none"><div>Hi</div></t>
<t style="display:none"><div>Hello</div></t>
<t style="display:none"><div>How</div></t>
<t style="display:none"><div>Are</div></t>
<t style="display:none"><div>You</div></t>
</div>

Now as per the requirement I need to convert this jquery code to core javascript :

This is what I tried :

size_timelinediv = document.getElementById("timeline").querySelectorAll("t").length;
console.log(size_timelinediv)//prints 5
var x = 3;//number of cards to be displayed

document.getElementById("timeline").querySelectorAll("t:lt(" + x + ")").style.display = "block"; //this doesn't work

But this doesn't work. It gives the following error :

"Uncaught SyntaxError: Failed to execute 'querySelectorAll' on 'Element': 't:lt(3)' is not a valid selector."

How do I achieve the same functionality using core javascript?

Upvotes: 2

Views: 722

Answers (1)

trincot
trincot

Reputation: 350771

CSS selectors don't have :lt. There are many ways to get the x first entries of the selected elements, for instance by using .slice(0, x) (after converting the node list to an array):

let timelinediv = document.querySelectorAll("#timeline t");
console.log(timelinediv.length); // prints 5
let x = 3; // number of cards to be displayed
for (let t of [...timelinediv].slice(0, x)) t.style.display = "";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="timeline" id="timeline" >
<t style="display:none"><div>Hi</div></t>
<t style="display:none"><div>Hello</div></t>
<t style="display:none"><div>How</div></t>
<t style="display:none"><div>Are</div></t>
<t style="display:none"><div>You</div></t>
</div>

Upvotes: 4

Related Questions