Select all items that were not wrapped by a specific item.

I want to select a tag <p>and set some of its properties, except when it is wrapped in a tag <span>.

How can i do this?

<div>
      <p></p>
</div>
<div>
     <span>
       <p></p>          // except this one - because it warped into span tag
     <span>
</div>
<div>
     <div>
        <p></p>
     </div>
 </div>
<ul>
    <li>
        <p></p>
    </li>
</ul>
Run codeHide result

Maybe something like this:

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

But most of the users of my website use older browsers such as IE8 (as you know, it does not support CSS3). So how can I do this?

+4
source share
2 answers

You can use :not()to exclude elements within a range

$('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 warped into <span> tag
    <span>
</div>
<div>
    <div>
        <p>p3</p>
    </div>
</div>
<ul>
    <li>
        <p>p4</p>
    </li>
</ul>
Run codeHide result
+3
source

One modern CSS method would look like this:

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

Your proposed solution ...

p:not(span p)

. , , - :not, CSS, . , . Selectors 4, . .

, :not - CSS- IE8 JS/jQuery. : : not() IE7/IE8

+1

Source: https://habr.com/ru/post/1650377/


All Articles