Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

Get all elements without child node in jQuery

I need to select elements without child node (including text since in <p> text is a child node).

I used empty, but it also consider space as child node.

Example:

Markup:

 <span> </span>
 <span></span>

Script:

$("span:empty").html("this was empty!");

Unfortunately, only the second element were selected and changed since the first element has space and it was considered child node.

How do I select elements without child node? I want to consider a space as nothing. Preferably, I want the code not to use loop to select them, there might be other ways.

question from:https://stackoverflow.com/questions/11061594/get-all-elements-without-child-node-in-jquery

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about

$("span:not(:has(*))")

Selects all spans that have no children.

Explanation

The :has() selector "selects elements which contain at least one element that matches the specified selector." The wildcard * means all elements.

The expression $('div:has(p)') matches a <div> if a <p> exists anywhere among its descendants, not just as a direct child.

The :not() selector "selects all elements that do not match the given selector."

In this case, :has() selects everything and then we use :not() to find the elements that don't match "everything"... in other words, nothing.

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...