Using CSS and the following example, is there a way to select only <p>
's that are followed by <ul>
's?
If not, what is the jQuery selector, or would it require an if
statement?
<p>Hello there.</p>
<p>Select this para!</p>
<ul>
<li>list item</li>
</ul>
<ul>
<li>don't select this list! :)</li>
</ul>
<p>And don't select this paragraph! :)</p>
If you want to select an element immediately after another element you use the + selector.
The CSS id Selector The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.
Inline CSS is used to style a specific HTML element. For this CSS style, you'll only need to add the style attribute to each HTML tag, without using selectors. This CSS type is not really recommended, as each HTML tag needs to be styled individually.
You can create a selector that will target specific elements with the class applied.
It's not possible in CSS3, the best you can do is select only the <ul>
which follow <p>
:
p + ul { /*...*/ }
However it will be possible when browsers start implementing the CSS4 subject operator:
!p + ul { /*...*/ }
In the meantime, you'll have to use jQuery and walk the DOM back.
Unfortunately, you are going to need to turn to javascript. The closest CSS selector to what you want (adjacent sibling selector) would do the exact opposite of what you want. For example, you could select all <ul>
after a <p>
like this:
p + ul { //style }
You can however make this selection in jQuery like this:
$('p + ul').prev('p')
So you first select all <ul>
immediately after <p>
and then select the previous <p>
from them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With