4

I want to select <p> tag and set it some properties except when it's wrapped into <span> tag.

How can I do that?

<div>
      <p></p>
</div>
<div>
     <span>
       <p></p>          // except this one - because it's warped into span tag
     <span>
</div>
<div>
     <div>
        <p></p>
     </div>
 </div>
<ul>
    <li>
        <p></p>
    </li>
</ul>

Maybe something like this:

p:not(span p) { 
    // CSS properties here
}

But the most of my website's user use old browsers like IE8 (as you know it doesn't support CSS3). So how can I do that?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Martin AJ
  • 6,261
  • 8
  • 53
  • 111
  • For older Browsers you can use JavaScript. Or don't use `:not()` and just be inclusive instead of exclusive. – StackSlave Aug 06 '16 at 01:23

2 Answers2

3

You can use :not() to exclude the elements inside a span

$('p:not(span p)').each(function(){
 console.log($(this).text())

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <p>p1</p>
</div>
<div>
    <span>
       <p>p2</p>          // except this one - because it's warped into <span> tag
    <span>
</div>
<div>
    <div>
        <p>p3</p>
    </div>
</div>
<ul>
    <li>
        <p>p4</p>
    </li>
</ul>
Kld
  • 6,970
  • 3
  • 37
  • 50
1

One modern CSS method would look like this:

:not(span) > p { background-color: aqua; } /* select all p elements who's parent
                                              is not a span */
<div>
    <p>YES</p>
</div>
<div>
    <span>
       <p>NO, because it's wrapped into <code>span</code> tag</p>
    </span>
</div>
<div>
    <div>
        <p>YES</p>
    </div>
</div>
<ul>
    <li>
        <p>YES</p>
    </li>
</ul>

Your proposed solution...

p:not(span p)

would not work for a couple of reasons. Primarily, however, the :not pseudo-class, in today's CSS, only accepts simple selectors as an argument. Neither complex or compound selectors would work. This changes in Selectors 4, which currently has very little browser support. Read more.

Also, for :not-like CSS targeting to work in IE8 would require JS/jQuery. Here are some options: Use :not() pseudo-class in IE7/IE8

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701