Home > database >  How can I use JavaScript to simulate the CSS attr() function?
How can I use JavaScript to simulate the CSS attr() function?

Time:10-20

How can I use JavaScript to simulate the attr() function? For example I want to indent the following paragraph using the value of data-indent as we do by p { text-indent: attr(data-indent em) }.

<p data-indent=4>Hello World :-)</p>

CodePudding user response:

Select the elements based on the attribute, loop over them and set an inline style based on the value in the data-attribute.

const elements = document.querySelectorAll('[data-indent]');
for (const element of elements) {
  element.style.textIndent = `${element.dataset.indent}em`;
}

CodePudding user response:

There's an example piece of code:

document.querySelector("p").style.text-indent = document.querySelector("p").getAttribute("data-indent") "em";
  • Related