Dynamically creating css selectors with JS

Here is some CSS I’m using for a personal portfolio, I have eight items that require a background url and size. Since tis css follows a very simple formula I was wondering if a bit of JavaScript could eliminate the need for me create a new CSS selector every time I add a portfolio piece. Is it possible to simply modify the HTML <article id="item22"></article> and have JavaScript create the corresponding selector in CSS?

	#item01 {
		background: url("../../images/thumbs/01.jpg");
		background-size: cover;
	}

	#item02 {
		background: url("../../images/thumbs/02.jpg");
		background-size: cover;
	}	

Hi,

Are you modifying the html id manually or by JavaScript?

Hi @CooKachoo, you mean you want to dynamically generate CSS rules for each element? This can be done by creating a style element (or query an existing one), and using insertRule() like so:

.item {
  background-size: cover;
}
<article class="item" id="item-01"></article>
<article class="item" id="item-02"></article>
<article class="item" id="item-03"></article>
const style = document.createElement('style')
const items = document.querySelectorAll('.item')

document.head.appendChild(style)

items.forEach(item => {
  // Create file name from the item ID
  const fileName = item.id.replace(/\D*/, '') + '.jpg'

  // Insert a CSS rule for the item ID
  style.sheet.insertRule(`
    #${item.id} {
      background: url('../../images/thumbs/${fileName}')
    }
  `)
})

Here’s a pen.

PS: For all intents and purposes, you might just set the element style directly though:

const items = document.querySelectorAll('.item')

items.forEach(item => {
  const fileName = item.id.replace(/\D*/, '') + '.jpg'
  item.style.background = `url('../../images/thumbs/${fileName}')`
})
3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.