We help IT Professionals succeed at work.

CSS ID reconnize

Peiris
Peiris asked
on
Medium Priority
396 Views
Last Modified: 2012-08-22
I have list of div tags are generated using a php loop. I id each div tag using "divItem_+(some random number)". My question is is it possible to set a CSS tag for these divs using the starting name if the tags. for example

#divItem*{
//styling
}

Open in new window

Comment
Watch Question

Commented:
I'd suggest adding a class to them all, in addition to the ID, so that you can target anything with that class.  For example:
<div class="allofthem" id="divItem_1"></div>
<div class="allofthem" id="divItem_2"></div>
<div class="allofthem" id="divItem_3"></div>

Open in new window

That way you can use
.allofthem{
//styling
}

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019
Commented:
Yes you can try this
*[id*='divItem_'] {
	background: blue;
}

Open in new window

or if you specifically want to target div's
div[id*='divItem_'] {
	background: blue;
}

Open in new window

Full test code here
<!doctype html>
<html>
<title>Title</title>
<style type="text/css">
div {
	width: 100px;
	height: 100px;
	float: left;
	margin: 10px;
	background: red;
}
div[id*='divItem_'] {
	background: blue;
}

</style>
<body>
<div id="divItem_1"></div>
<div id="divItem_2"></div>
<div id="divItem_3"></div>
<div id="divItem_4"></div>
<div id="term"></div>
</body>
</html>

Open in new window

Kyle HamiltonData Scientist
Most Valuable Expert 2014

Commented:
If you're trying to target all of them, then absolutely go with a class per WebDevEM's post.

Beware of using general selectors like * or div or regex: [class^="grid-"]. They are the slowest to render. It won't make much of a difference in a small website with a couple of divs, but the minute you start adding more DOM elements, you'll be asking for trouble.  Have a look here for more on CSS preformance:

http://csswizardry.com/2011/09/writing-efficient-css-selectors/
Top Expert 2013

Commented:
I'd suggest adding a class to them all, in addition to the ID, so that you can target anything with that class.

WebDevEM is 100% correct. That is best practice.  If you like nightmare maintenance easily broken pages, and looking foolish then by all means explore other options, but not only is this best practice it is no more work than trying something screwy. You are already generating with php so you have one line of code to change, and a simple non-complex and efficient rule to put in the CSS.

Cd&

Explore More ContentExplore courses, solutions, and other research materials related to this topic.