iamafasha
iamafasha

Reputation: 794

Is there a way to use :first in javascript queryselector?

I have a table containing a list of users and I would like to hide all their duplicates on an event. an example in the image below is hiding the second tr#user-3.

enter image description here

But when I tried using temp1.querySelectorAll('tr:not(#user-3:first)') it didn't return any node instead and it brings invalid selector error. What could be the cause and how do I solve it ?

enter image description here

Upvotes: 0

Views: 315

Answers (3)

Reyot
Reyot

Reputation: 486

I couldn't figure out what was the issue for the given problem. However the code below seems to work.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<table class="tables">
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr id="user3">
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>
    <tr id="user3">
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>
    <tr id="user3">
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>
</table>
</body>
<script>
    window.onload = function(){
        var table = document.querySelectorAll(".tables tr#user3:not(:nth-child(2))");
        //console.log(table);
        table.forEach(el => {
            el.style.backgroundColor = "red";
        })
    }
</script>
</html>

The code also works with last-child

Upvotes: 0

deepa
deepa

Reputation: 56

You can use querySelector() instead. It always gets you the first element that matches the selector.

const firstEl = temp1.querySelector('tr');

QuerySelector Documentation

Upvotes: 0

KashyapVadi
KashyapVadi

Reputation: 505

:first is not part of the CSS spec, this is jQuery specific.

To access the first and last elements, try.

    var nodes = temp1.querySelectorAll('tr');
    var first = nodes[0];
    var last = nodes[nodes.length- 1];

Upvotes: 1

Related Questions