1

I would like to be able to write <div class="inlined">content</div> or so, and have it transformed into some other html, using the content, and as defined by inlined. I would like to do this in pure CSS ie., no javascript.

For instance, that would be a function inlined:

<div data-descr="content"/> -> <div class="container"><div class="topright">content</div></div>

With some implementation "like":

div[data-descr] {
  content: <div class="container"><div class="topright">attr(data-descr)</div></div>;
}

If no pure CSS can be used, what would be a less/sass/js solution?

Soleil
  • 6,404
  • 5
  • 41
  • 61

2 Answers2

1

Since your data attribute includes HTML, you can't use the CSS content property for this because your HTML will be treated as a string - it won't get parsed.

You should also avoid adding HTML to data attributes anyway.

You can do it with JavaScript, though, via replaceWith.

Try creating an object for that markup you want to add. You can then reference that to get the HTML

// helper function to handle new element creation
const createNewElement = content => {
  const container = document.createElement("div");
  container.classList.add("container");

  const inner = document.createElement("div");
  inner.classList.add("top-right");
  inner.innerHTML = dataObject[content];

  container.append(inner);

  return container;
}

// create an object to get the HTML for a specific describtion attribute
const dataObject = {
  content: `<div class="red">red text</div>`,
  content2: `<div class="green">green text</div>`,
  content3: `<div class="blue">blue text</div>`,
}

// get the elements you want to change
const targetElements = document.querySelectorAll("[data-descr]");

// loop through them and swap them
targetElements.forEach(element => {
  const content = element.dataset.descr;
  const newElement = createNewElement(content)
  element.replaceWith(newElement)
})
.red {
  color: red;
}

.green {
  color: green;
}

.blue {
  color: blue
}
<div data-descr="content"></div>
<div data-descr="content2"></div>
<div data-descr="content3"></div>
volt
  • 963
  • 8
  • 17
0

As stated by @ErikMartino in this answer: https://stackoverflow.com/a/5865996/8106583

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

If content did support HTML you could end up in an infinite loop where content is added inside content.

wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29