Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select elements which do not have a specific child element with JQuery

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>.

like image 589
Stephan Avatar asked Aug 31 '11 14:08

Stephan


People also ask

Which is used to select that element which does not contain any children?

filter(function() { return !$(

How do you select an element that does not have a specific class?

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(.

How do you select all child elements except last?

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.

How do you get the children of the $( this selector in jQuery?

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.


2 Answers

You could try:

$("p:not(:has(>div))") 
like image 55
jmans Avatar answered Oct 25 '22 08:10

jmans


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.

like image 45
Peter Olson Avatar answered Oct 25 '22 10:10

Peter Olson