1

I want to do this

document.getElementById('demo1').style.color = "red";
document.getElementById('demo2').style.color = "blue";
document.getElementById('demo3').style.color = "green";
document.getElementById('demo4').style.color = "fuchsia";
<p id="demo1">Styled text</p>
<p id="demo2">Styled text</p>
<p id="demo3">Styled text</p>
<p id="demo4">Styled text</p>

But don't want to do it that way, this is better:

function style(obj, color) {
  obj.style.color = color;
}
<p call="style(this, 'red')">Styled text</p>
<p call="style(this, 'blue')">Styled text</p>
<p call="style(this, 'green')">Styled text</p>
<p call="style(this, 'fuchsia')">Styled text</p>

But this doesn't work. I am looking for some DRY way of styling text, and the first way is very tedious. The JavaScript way is pleasant, as it allows for more flexibility (like adding fontFamily in the parameters). Is there some HTML attribute that can work like call above? Is there some other way of styling text that is just as good? I thought about onload, but that works only for certain selected tags.

This related question comes close, but it is about a web page, not about a specific HTML tag.

1 Answer 1

2

You can try creating your own call attribute of the sort. Only thing is this won't work - you'll have to reference it through the parent function.

function style(obj, color) {
  obj.style.color = color;
}
document.querySelectorAll('p').forEach(elem => eval(elem.getAttribute('data-call')));
<p data-call="style(elem, 'red');">Styled text</p>
<p data-call="style(elem, 'blue')">Styled text</p>
<p data-call="style(elem, 'green')">Styled text</p>
<p data-call="style(elem, 'fuchsia')">Styled text</p>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.