Skip to content
Advertisement

How can I give an html element an ID taken from a php variable?

I am creating a website which uses php to get data from a phpmyadmin database and use the info from this database in my html.

I have this php query which finds the value from the ‘ID’ field and then creates a variable called ‘$studentID’ with this value (which will be the number 2 in this case):

JavaScript

Then I have attempted to use this variable as the ID for an html element called ‘rowcontainer’:

JavaScript

Then I have set the background colour of this element using the id “2” to blue (using css):

JavaScript

When I use the inspect tool, the element ‘rowcontainer’ does appear to have an id of “2” like I want but the colour is still the default white and not blue.

inspect element html

inspect element css

Is there something I have missed, or a better way to achieve this?

Advertisement

Answer

While HTML5 is happy with an id starting with a digit it appears that CSS3 is not.

If you do stick with having and id that starts with a digit you can get CSS to pick it up by using an attribute selector – this says ‘choose the element that has an id attribute with that string’.

JavaScript
JavaScript

Or you can prepend (not append) the id with an a-z character or string in your php like this:

JavaScript

and then select this div by

JavaScript

Incidentally, beware of adding spurious space characters to strings. Your PHP puts a space after the 2. In some cases spaces matter (string matching on the whole) in some they don’t.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement