Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix this error "Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': 'div.com[min=]' is not a valid selector"? [duplicate]

Tags:

javascript

I am trying to hide the comments with the children like reddit, and I wrote this function:

function toggle(id, lft, rgt) {
    var kids = (rgt - lft - 1) / 2;
    if (kids >= 1) {
        var element = document.querySelector("div.com#com" + id).getAttribute('value');
        var low = Number(element.split('-')[0]);
        var high = Number(element.split('-')[1]);
        for (var i = low + 1; i <= high - 1; i += 1) {
            const x = document.querySelectorAll('div.com[min=' + i + ']');
        }
        Array.from(x).forEach(comment => {
            if (comment.style.display === "none") {
                comment.style.display = "block";
            } else {
                comment.style.display = "none";
            }
        });
    }

for example this is the parent comment:

<div> 
      <a onclick="return toggle(1, 1, 4)" href="javascript:void(0)">[-]</a>
       <div id="com1" class="com md" value="1-4" min="1">yellow</div>
</div> 

and this is a child comment:

<div> 
     <a onclick="return toggle(2, 2, 3)" href="javascript:void(0)">[-]</a>
    <div id="com2" class="com md" value="2-3" min="2">hello </div>
</div> 

I want to hide all the comments that have the min attribute between the parent value 1 and 4 and this child have the min=2 so it must be hidden. BUT the js function isn't working, so what's the problem?

other questions?

  • Should I write the foreach inside the for loop or it's fine like this way?
  • if the error in the title is fixed, will the function work and the child comments will be hidden, if not, why?
like image 261
lawlawi Avatar asked Nov 02 '25 01:11

lawlawi


1 Answers

Well, as the error message says, your selector is invalid. Add quotation marks around the value of the attribute.

const x = document.querySelectorAll(`div.com[min="${i}"]`);

(It looks more readable with ES6 template literals).

like image 192
mbojko Avatar answered Nov 03 '25 15:11

mbojko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!