Navin Rauniyar
Navin Rauniyar

Reputation: 10525

difference between :parent vs normal selector

Suppose of the following html...

<div>
<p>esrer</p>
<p><span>test</span><span>ste</span>asdlfk</p>
</div>

Now comparing with the following two methods:

using :parent demo

$("span:parent").fadeTo(1500, 0.3);

without using :parent demo

$("span").fadeTo(1500, 0.3);

Results the same.

I'm curious about the :parent pseudo class added in jquery extension and how does this work?

Upvotes: 0

Views: 52

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173572

How this selector works is better explained when using something else than .fadeTo(). For instance:

HTML:

<span>I am a parent</span><span></span>

JavaScript:

$('span').not(':parent').text('I am not a parent');

Only the second span will be updated with the text "I am not a parent"; this is because only non-empty elements are considered to be parents and the second span is empty.

Demo

Upvotes: 2

Omar Sedki
Omar Sedki

Reputation: 608

:parent Select all elements that have at least one child node (either an element or text). This is the inverse of :empty

:parent = not :empty

Upvotes: 1

Felix
Felix

Reputation: 38102

From the docs:

:parent selector select all elements that have at least one child node (either an element or text).

So in your case, the selector $("span:parent") will match any span that has text inside which are <span>test</span> and <span>ste</span>

Upvotes: 0

Related Questions