简体   繁体   中英

How to read class name of a html element in php?

I am trying to make a project in php in which the class name will be read and transformed into variable and will set background of that specific color mentioned in the class. for eg, if I type <div class="#999"> , I should get the background color #999 of the element (div). I did everything fine but having trouble to get the element's class, pls help me out how to get the class of the element. Thanks in advance.

Just use the data- attribute and not the class name. In your case I would add data-bg="#999" and then read it in JS and set the background color.

Here is some documentation for data-

 const container = document.getElementById('container'); container.style.backgroundColor = container.dataset.bg;
 <div id="container" data-bg="#999">lorem ipsum</div>

This seems like a job for CSS, rather than PHP or even JavaScript.

You can either

a) set an inline style on the element itself defining the background colour (this is simple and quick but not the most maintainable or flexible in the long run):

 <div style="background-color:#999">Div Contents Here</div>

OR

b) define a CSS class which has a rule setting the background colour for all elements which have that class:

 .classA { background-color:#999; }
 <div class="classA">Div Contents Here</div>

This seems like the most efficient way to define a background colour. If you need to vary which colour the div is given, define multiple classes which have different background colours, and get your PHP to output a different class name for the div, depending on your rules.

(NB Your question wasn't 100% clear so if I've misunderstood what you mean, then please let me know and I can update the answer.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM