0

I am trying to better my Javascript knowledge and I am struggling. I have a list in HTML. I want the bullet points of each element to be a random hex color.

function generateColor() {
  var hex = "";
  var range = "abcdef0123456789";

  for (var i = 0; i < 6; i++) {
    hex += range.charAt(Math.floor(Math.random() * range.length));
  }

  $('li:before').css('color', '#' + hex);

}

$('li:before').on('keypress', function(event) {
  if (event.keyCode == 32) {
    generateColor();
  }
});

generateColor();
ul {} li {
  list-style: none;
}
li:before {
  content: "■ ";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

Dilemma: I don't think I can change the List-Style elements color period.

I found a way around this, by using the :before tag in my css for the "List Item"...

By doing that I am able to use any ASCII symbol as my list element.

I looked online for a few examples to change the Color: aspect of my li:before style. However, I don't think the function likes the :before part of my CSS.

I am stumped, Is what I want to do even possible?

  • @Paulie_D I don't think the question you marked duplicate having the exact solution for this question this should be reopen – Gaurav Aggarwal Aug 09 '16 at 06:09
  • I disagree, it's the same question in a different form. The answer is the same. Pseudo-elements cannot be selected by JS as they aren't in the DOM. – Paulie_D Aug 09 '16 at 06:20
  • @Paulie_D and marking it as a duplicate helped OP to find a solution? – freewheeler Aug 09 '16 at 06:23
  • The solution(s) is/are in the linked question....that's the point. The OP will just have to adapt one of the suggestions there. – Paulie_D Aug 09 '16 at 06:43

1 Answers1

0

You can't modify the :before element with jquery as it's not technically part of the DOM. There is definitely some alternatives though, have a look here for a more complete answer.

Community
  • 1
  • 1
tibo
  • 5,326
  • 4
  • 37
  • 53