Home > database >  Can you style ordered list numbers in javascript? If so, how?
Can you style ordered list numbers in javascript? If so, how?

Time:10-13

Lets say you have an HTML element like so:

<p id="theparagraph">Hello there!</p>

You can style it by using CSS or javascript, respectively, like so:

#theparagraph{
  color:green;
}
document.getElementById("theparagraph").style="color:blue";

It has come to my attention that, with an ordered list, you can style the "marker" attribute (or whatever it is called). This is the individual number that comes before the text of an ordered list item. Here is an example:

<ol>
  <li id="thelistitem">
    Hello there!
  </li>
</ol>

You can style it in CSS by doing the following:

#thelistitem{
  color:blue;
}
#thelistitem::marker{
  color:red;
}

But, my question is, what is the equivalant for that in javascript? I have tried the following, with no success:

document.getElementById("thelistitem").style="::marker{color:blue}";
document.getElementById("thelistitem").style::marker="color:blue";
document.getElementById("thelistitem").style.marker="color:blue";

None of them have worked. What DOES work? And I am not asking for a class that is assigned and taken away from elements. I am asking for the style of it. How would one edit it?

CodePudding user response:

While JS cannot directly alter the color of the marker as it's a pseudo element, not actually in the DOM, we can get it to set a CSS variable of the actual 'real' element and use that to change the color in the pseudo element.

#thelistitem {
  color: blue;
}

#thelistitem::marker {
  color: var(--color);
}
<ol>
  <li id="thelistitem">
    Hello there!
  </li>
</ol>
<button onclick="document.getElementById('thelistitem').style.setProperty('--color', 'red');">Click me</button>

CodePudding user response:

JavaScript cannot manipulate pseudo elements because they aren't actually presented in the DOM tree, But you can do a workaround to achieve your goal by using CSS Variables!

ol li {
  color: #777;
}

ol li::marker {
  color: var(--custom-variable);
}
<ol>
  <li id="list_item">List Item 1</li>
</ol>

<button onclick="document.getElementById('list_item').style.setProperty('--custom-variable', '#000');">
  Change Color
</button>

We just assigned --custom-variable to color property, and manipulated its value using setProperty in JavaScript for the parent element.

  • Related