Home > Blockchain >  jQuery multiple pseudo :not selector with descendant combinator
jQuery multiple pseudo :not selector with descendant combinator

Time:03-26

I have some markup like

<div ><img></div>

and

<div ><img></div>

I need to dynamically wrap img with a div and use $(":not('.a, .b) > img") to select them.

Unfortunately I also have some markup like

<div ><div><div><img></div></div></div>

so the > child combinator won't work. I guessed $(":not('.a, .b, .c) img") will work for all but that is not the case.

What do I miss? How can I select all img tags that are several class but at different child levels?

Thanks for help

CodePudding user response:

What do I miss?

:not('.a, .b, .c) matches the inner divs that don't have any classes, which are also ancestors of the img.

You might be able to use some combination of :not and jQuery's :has extension, but I think I'd probably do it manually, something like this:

// Using jQuery
$("img").each((_, el) => {
    const $el = $(el);
    if (!$el.closest(".a, .b, .c").length) {
        // ...wrap the element...
    }
});

or

// Using the DOM directly
for (const img of document.querySelectorAll("img")) {
    if (!img.closest(".a, .b, .c")) {
        // ...wrap `img`...
    }
}

since the DOM has closest now.

  • Related