0

I'm having some trouble dynamically changing the background field within the .tracking-list li a:before css for each a I'm looping through.

As an example I was able to change the background to "red" below and the name, but I'm unsure how to change the specific field "background" within .tracking-list li a:before.

Any suggestions on how I can dynamically change this? Thanks so much!

style.css

.tracking-list li a:before {
    content: "";
    background: url("../images/bitmap.svg") no-repeat;
    display: inline-block;
    width: 22px;
    height: 20px;
    margin-right: 4px;
    vertical-align: middle;
}

JS

//Loop Through Names
var ul = document.getElementById(category);

for (var i = 0; i < data.data.length; i++) {

  let record = data.data[i];
  let tech_name = record.name;
  let logo_image = record.logo;

  var listItem = document.createElement("a");
  listItem.textContent = tech_name;
  listItem.style.background = "red";
  ul.appendChild(listItem);
}

1 Answers1

0

You can't target pseudo-classes with inline style.

If you want to change them you need to either:

  • Modify the stylesheet
  • Change the conditions which cause the rule to be applied to the pseudo-class in the first place

The latter is usually the simplest approach.

document
  .querySelector("button")
  .addEventListener("click", changeMiddleLink);
  
function changeMiddleLink() {
    document.querySelector("li:nth-child(2) a").classList.add("changed")
}
.tracking-list li a::before {
    content: "";
    background: green;
    display: inline-block;
    width: 22px;
    height: 20px;
    margin-right: 4px;
    vertical-align: middle;
}

.tracking-list li a.changed::before {
    background: red;
}
<ul class="tracking-list">
    <li>
        <a href="http://example.com/">Test</a>
    </li>
    <li>
        <a href="http://example.com/">Test</a>
    </li>
    <li>
        <a href="http://example.com/">Test</a>
    </li>
</ul>

<button type="button">Click me</button>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335