Find div that contains image and add class for CSS recognition

Asked

Viewed 34 times

0

I need help finding tags <img> inside the structure below.

When found, add a "hasimg" class together with the "skuFiltro" tag class <ul> primary. I need to recognize if you have image or not so I can differentiate the CSS style of the front-end structure of a platform I’m working on.

<ul class="skuFiltro">
    <li>
        <ul class="filterBlock">
            <li>
                <a href="#">
                    <img src="/img/teste.img" alt="">
                </a>
            </li>
        </ul>
    </li>
</ul>
<ul class="skuFiltro">
    <li>
        <ul class="filterBlock">
            <li>
                <a href="#">380mm</a>
            </li>
        </ul>
    </li>
</ul>

1 answer

1


To go through all elements with the class 'skuFiltro', you can use:

$('.skuFiltro').each(function(index, element) {
    var img = element.querySelector("img");
    if(img != null){
       element.addClass("hasimg");
    }
});

The function .each() traverse each element that has the class .skuFiltro. A querySelector() is checking within the current element of . each, if there is any 'img' tag, if there is none inside the element in question, the img variable will receive NULL.

  • 1

    Thanks Vinicius, problem solved! :)

  • @Ivanrichardroncatto show! If my answer has contributed to your resolution, if you can mark it as "answer".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.