While working on a site I came to a situation where I needed to select div classes with a dynamic id number. For instance every new div class would carry it’s “id” from my database in its class name like so:
<div class="reply_to_08"></div>
So I could do this
.reply_to_08 {}
But I didn’t want to write a new css selector for every div. I wanted to select all of them that had the “.reply_to_” in it while ignoring the “08” that being the dynamic number.
So I found a solution on a blog post on a website which was:
div[class^=reply_to_]
Well it worked, but there was no explanation as to why that would work or how it would work. And I can’t seem to understand it.
Can someone explain as to why that works? And is this method recommended or is there another way of achieving what I want?
The key is the
^=pattern of the Attribute Selector ([class^=reply_to_]).In your case, the
^=will let you select every element whoseclassattribute value begins with"reply_to_"