Find div containing image and add class for CSS recognition

0

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

When found, add a "hasimg" class next to the "skuFiltro" class of the primary <ul> tag. I need to recognize if it has an image or not to be able to differentiate the CSS style from 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>
    
asked by anonymous 23.11.2018 / 12:33

1 answer

1

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

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

The .each () function runs through each element that has the class .skuFilter. The querySelector () is checking inside the current .each element, if there is some img tag, if it does not have any inside the element in question, the variable img will receive NULL.

    
23.11.2018 / 12:52