0

How to select and apply styles for html element which has no defined child element? For example:

<p>Lorem</p>
<p>Isum <span>dolor</span></p>

I want to apply some styles for the first p because it doesn't contain span element.

Is it possible to do by CSS?

Eugene Kuzmin
  • 268
  • 2
  • 13

5 Answers5

1

You would have to put a selector on that first p to do this in CSS only:

http://jsfiddle.net/6EmxP/

You can use the jQuery route to do the same thing.

Lowkase
  • 5,413
  • 2
  • 28
  • 47
  • It's possible to have many p and I do not know which one has a child. – Eugene Kuzmin Jun 12 '12 at 14:51
  • If you don't know which p will have the span child then you will have to go with a javascript/jQuery solution. Currently there is no way to move up the DOM with CSS, you can use jQuery to get around that limitation. – Lowkase Jun 12 '12 at 15:11
0

Why don't you give that <p> a class or something like that? If you want it to be dynamic add a class to using javascript. You can setup conditions better with that. CSS is not your answer in this case. This can be helpful in some ways :) http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/

Axente Paul
  • 533
  • 2
  • 8
0

I don't think you can do it with css. You can do it with jQuery...

See http://api.jquery.com/has/

0

You don't need to select the parent, I think..

<p class="Lorem">Lorem</p>
<p>Isum <span>dolor</span></p>


.Lorem + p {color: green;}
Robin Maben
  • 19,662
  • 16
  • 61
  • 93
  • If you're still curious about the parent selector. Read this answer - http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector – Robin Maben Jun 12 '12 at 14:47
0

Your first p element actually has a child: It's a text node. Otherwise, :empty could be used.

When you know the exact position of the element, :nth-child can be used. There is no need for a class (but it would be faster).

fb55
  • 1,107
  • 1
  • 11
  • 16