Home > Mobile >  Styling the HTML tags that are created in javascript
Styling the HTML tags that are created in javascript

Time:03-25

If i use HTML tags inside javascript file, how can i select them and use them in a css file?

for example: javascript: <li id="id"> name </li>

how can i select and use id in the stylesheet?

I tried it this way but it didnt work #id li { background: red;}

CodePudding user response:

I would avoid using ids as they have to be unique (no more than one per page). If you have to target specific list items use data attributes.

ul li[data-type="name"] { color: red; }
<ul>
  <li data-type="name">Bobby</li>
  <li data-type="age">26</li>
</ul

CodePudding user response:

either you can use the JS also add style to the Element.

document.getElementById(id).style.property = new style

Add inline style using Javascript

Or you need to load the script before the style.

CodePudding user response:

If you assign a id to any tag or element you don't need to use element or tag name to style it. Directly use id. by #id li { background: red; } it means inside the element(which has id) it search for another li element. Try

#id {
  background: red;
}

CodePudding user response:

if your creating element dynamically it's better to apple style that time for example

var el = document.createElement('div');

el.setAttribute(
 'style',
 'background-color: red; color: white; width: 150px; height: 150px; border: 1px red solid');
 var container = document.getElementById('container-id');
 container.appendChild(el);

CodePudding user response:

I would avoid using ids as they have to be unique

.bgred { background: red;color:#fff }
.bggreen { background: green;color:#fff }
<ul>
  <li >Bobby</li>
  <li >26</li>
</ul>

  • Related