Home > Article > Web Front-end > Can You Select Elements by Partial ID Values with CSS?
In the realm of CSS, identifying elements with precision is paramount. This question delves into the possibility of selecting elements not by their complete ID value but rather by a partial match.
The problem arises from PHP-generated elements with partial ID values. For instance:
<div class="1" id="as_1"> ... </div> <div class="2" id="bs_1"> ... </div> <div class="1" id="as_2"> ... </div> <div class="2" id="bs_2"> ... </div>
While the class attribute groups elements by commonalities, the need to select them individually poses a challenge due to the incomplete ID names.
Unfortunately, CSS ID selectors demand complete ID values, rendering suggestions like #as_{ ... } and #bs_{ ... } ineffective.
Attribute substring selectors offer an alternative approach:
div[id^="as_"] div[id^="bs_"]
These selectors match elements whose ID values begin with the specified string. However, relying on this method may lead to unintended consequences if other elements share similar prefixes within their IDs.
Given the presence of a class attribute, a simpler solution involves assigning a common class to each group of elements and targeting them via CSS through that class. The class designation could be derived from the PHP logic responsible for generating the IDs. This approach simplifies the selection process while maintaining the desired specificity.
The above is the detailed content of Can You Select Elements by Partial ID Values with CSS?. For more information, please follow other related articles on the PHP Chinese website!