Home > Article > Web Front-end > How to Select Elements in CSS When You Only Know Part of Their ID?
Selecting Elements in CSS by Partial ID Value
In web development, it becomes necessary to select elements with specific identifiers for styling or manipulation purposes. However, what if you only know a portion of the element's ID?
The Challenge:
Consider a scenario where you have elements generated dynamically with PHP, assigning unique IDs that include a prefix:
<code class="html"><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></code>
You need to select these elements individually without knowing the entire ID.
Limitations of ID Selectors:
Attempted usage:
<code class="css">#as_{ ... } #bs_{ ... }</code>
Alternative Solution: Substring Attribute Selectors:
ID selectors are not suitable for this scenario, but substring attribute selectors can be employed:
<code class="css">div[id^="as_"] div[id^="bs_"]</code>
Additional Suggestion:
If your elements already have class attributes, consider assigning a common class to each group and selecting by that class instead. This simplifies the process and ensures the selection is independent of the ID generation method used in PHP.
The above is the detailed content of How to Select Elements in CSS When You Only Know Part of Their ID?. For more information, please follow other related articles on the PHP Chinese website!