Is there a JQuery selector to select all elements which do not have certain child element as a direct child? For example:
<p> text in paragraph </p> <p> <div>text in div</div> </p>
I want to select only <p>
s like the first one (without a <div>
child). Is this possible?
Further information: Actually I'm trying to insert a <div>
into all those <p>
that do not have one by an expression like this:
$('p').wrapInner('<div />')
But this would add an additional <div>
to the second <p>
.
filter(function() { return !$(
To select element that does not have specific class with JavaScript, we can use the document. querySelector method with the :not pseudoclass. const li = document. querySelector("li:not(.
When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.
jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
You could try:
$("p:not(:has(>div))")
You can combine the :has()
[docs] selector with the not
function[docs] to acheive this:
$("p").not(":has(div)").wrapInner("<div/>");
Alternatively, you can use a single selector by using the :not()
[docs] selector:
$("p:not(:has(div))").wrapInner("<div/>");
You can use either interchangeably, but IIRC, the first is faster.
See it in action on jsFiddle.
Note that div
is a block-level element and p
is not. That means it is not valid HTML to have a div
nested in a p
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With