Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
197
rated 0 times [  199] [ 2]  / answers: 1 / hits: 8169  / 5 Years ago, thu, june 13, 2019, 12:00:00

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?


More From » javascript

 Answers
31

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).


[#7302] Tuesday, June 11, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
dusty questions
Mon, Dec 14, 20, 00:00, 4 Years ago
Mon, Mar 23, 20, 00:00, 4 Years ago
Fri, May 17, 19, 00:00, 5 Years ago
;