1

I have the following HTML code:

<td data-label="https://www.example.com/myimage.jpg">
    <span>3</span>
</td>

In my CSS, I want to get that data-label attribute and use it for CSS content, like this:

content: url("attr(data-label)");

However, this is not working. I tried several ways, but I'm unable to display the image.

Using just...

content: url("https://www.example.com/myimage.jpg");

... works like a charm!

Any ideas? Is this possible at all?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Arnie
  • 661
  • 9
  • 20

1 Answers1

1

I'm afraid you're not able to combine url() and attr().

This means it's not possible to achieve the desired effect with CSS alone.

However, you can achieve it with just a little bit of JavaScript code :

var attribute = "data-label";
var elements = document.querySelectorAll("["+attribute+"]");

for (var i = 0; i < elements.length; i++) {
  elements[i].style.content="url("+elements[i].getAttribute(attribute)+")";
}
<table>
  <tr>
    <td data-label="https://i.stack.imgur.com/mRsBv.png?s=328&g=1">
      <span>3</span>
    </td>
  </tr>
  <tr>
    <td data-label="https://www.gravatar.com/avatar/a42287aaa5cd72c0d29dd65f065e9c51?s=328&d=identicon&r=PG&f=1">
      <span>3</span>
    </td>
  </tr>
</table>
John Slegers
  • 45,213
  • 22
  • 199
  • 169