Simo
Simo

Reputation: 57

Change the css of all the elements based on an IF condition

enter image description here

Im trying to hide some li elements on this website with the help of a chrome extensions "Custom Javascript"

I've tested my code on a local file and it only works with the first li:

var b = document.querySelector("span.price_value").innerHTML;
var processed = b.replace(/ /g, '');
var output = parseInt(processed, 10);
if (output >= 5000) {
    document.querySelector(".item").style.display = "none";
}

How can i change the css property of all the li elements that matches that condition?

querySelectorAll just returns an undefined error.

Upvotes: 0

Views: 279

Answers (4)

Todilo
Todilo

Reputation: 1333

querySelectorAll returns a list of items. Iterate through that and set each element to display none.

var items = document.querySelectorAll(".item");
items.forEach(function(item) {
  item.style.display = "none"
});

Upvotes: 1

Máté Safranka
Máté Safranka

Reputation: 4106

querySelector() returns the first element that matches the selector. You can use querySelectorAll() to retrieve a list of elements that you can then iterate over.

for (var item of document.querySelectorAll("span.price_value")) {
    var processed = item.innerHTML.replace(/ /g, '');
    var output = parseInt(processed, 10);
    if (output >= 5000) {
        item.style.display = "none";
    }
}

Upvotes: 1

Christopher Meyers
Christopher Meyers

Reputation: 339

You'll want to use querySelectorAll which returns a node list, instead of querySelector, which returns the first node it finds.

You'll need to use some kind of 'for' loop to affect each node in the list.

Upvotes: 1

Satpal
Satpal

Reputation: 133453

As you have tagged , You can use .filter(fn) to get all span.price_value element passing test condition, then using .closest() to target ancestor element to .hide()

//Get all span having text > 500
$("span.price_value").filter(function () {
    var processed = $(this).html().replace(/ /g, '');
    var output = parseInt(processed, 10);
    return output >= 5000
})
.closest(".item") //Target parent items
.hide() //Hide

Upvotes: 1

Related Questions