Jaume
Jaume

Reputation: 3790

Javascript Change an image url property of a list item programmatically

I am adding some list elements programmatically into a list, where every item has an image instead of a bullet. For that, I need to change also the image programmatically.

How can I set the url image path of the property 'background-image' from the li:before?

The css list properties look as:

ul.fileList {
    background-color: white;
    list-style: none;
}
    ul.fileList > li:before {
        content: '';
        display: inline-block;
        background-size: 30px;
        background-image: url('/Resources/imageFileIcon.png');
        background-repeat: no-repeat;
    }

I am adding the list items as:

   for (var i = 0; i < files.length; i++) {
            $("ul.fileList").append("<li><a href='#'>" + files[i] + "</a></li>");
            //how to set the background-image: url()??
   }

Upvotes: 0

Views: 189

Answers (2)

Imran Rafiq Rather
Imran Rafiq Rather

Reputation: 8118

All you require is list-style-image to be used as below.

for (var i = 0; i < files.length; i++) {
  $("ul.fileList").append(`<li style="list-style-image: url('/Resources/imageFileIcon.png');"><a href='#'>${files[i]}</a></li>`);
}

You don't need any other CSS: Just make sure to use the correct relative path for your image w.r.t Javascript file.

Upvotes: 2

Sean
Sean

Reputation: 8058

You can do this via CSS variables set on the list item element:

ul.fileList > li:before {
  content: '';
  display: inline-block;
  background-size: 30px;
  background-image: var(--background-image, url('/Resources/imageFileIcon.png'));
  background-repeat: no-repeat;
}
for (var i = 0; i < files.length; i++) {
  $("ul.fileList").append("<li style='--background-image: url(" + path + ")'><a href='#'>" + files[i] + "</a></li>");
}

Upvotes: 1

Related Questions