admin管理员组

文章数量:1387458

I'm running a WooCommerce site and found a new way of importing product images and need to apply CSS to thumbnail pictures of new products only and leave old products untouched.

Looking at the source code, I found each product has a product ID:

<li class="product type-product post-100 data-product-id="100">

Is there any way to apply CSS to, let's say, data-product-id > 100? E.g.

if (data-product-id > 100) {
  padding: 50px;
}

Either by using a third party plugin or add custom JS/CSS code?

I'm running a WooCommerce site and found a new way of importing product images and need to apply CSS to thumbnail pictures of new products only and leave old products untouched.

Looking at the source code, I found each product has a product ID:

<li class="product type-product post-100 data-product-id="100">

Is there any way to apply CSS to, let's say, data-product-id > 100? E.g.

if (data-product-id > 100) {
  padding: 50px;
}

Either by using a third party plugin or add custom JS/CSS code?

Share Improve this question asked Apr 26, 2020 at 22:24 BiosBernhardBiosBernhard 1 1
  • 1 Plugin recommendations are offtopic here, and CSS questions should go on stack overflow – Tom J Nowell Commented Apr 26, 2020 at 23:29
Add a comment  | 

1 Answer 1

Reset to default 0

Can you just specify a new class when you create those thumbnails, and style accordingly?

If this is what you want to do:

You need to grab every element that has the [data-id] attribute into an object array var ids = document.querySelectorAll("[data-id]");

Then you need to iterate over them, and check the value:

ids.forEach((el) => {
        if (parseInt(el.dataset.id) > 100) {
            el.classList.add("new-style");
        }
    });

You can add the new styling in your CSS (so you can change it as needed without touching the js)

You want to wrap the js in a document ready so the elements are there before it starts, or it'll return undefined.

The final code:

document.addEventListener("DOMContentLoaded", function () {
    var ids = document.querySelectorAll("[data-id]");

    ids.forEach((el) => {
        if (parseInt(el.dataset.id) > 100) {
            el.classList.add("new-product");
        }
    });
});

Then you can target the new products using .new-product{} in your CSS files.

I hope that helps!

本文标签: woocommerce offtopicApply CSS to certain product thumbnails only