1

Is there a way to create custom CSS properties in JavaScript?

Example

Note: this code won't work, it's just showing the sort of thing I'm looking for.

I'm looking for something like this: (that doesn't mean exactly this, just the general idea)

JavaScript:

createCSSProperty("bg", function(property, change, attr1) {
  change.setBackground(attr1, function fail(data) { //This function would trigger if the value was invalid
    property.fail(data); //This would throw an warning that the property can't load
  });
}

HTML:

<div style="width: 40px; height: 40px; bg: #f00;">Red Background</div>

The result would appear as it does in this snippet

<div style="width: 40px; height: 40px; background: #f00;">Red Background</div>

Add-on question

As a bit of an add-on to this question, what about custom CSS functions, CSS values (that hold a value depending on one or more things, such as the values unset and inherit), CSS selectors, and maybe even CSS units?

Some guy
  • 148
  • 10
  • You can achieve something like this [with css](https://stackoverflow.com/a/8426901/4935162) ... But it's very weird. You can also `querySelectorAll` the elements with that property in their in-line style attribute and change their bg via js. (`element.style.backgroundColor`). But it only works for elemts that exist at page load unless you can listen to new elements or something. – Yarin_007 May 14 '22 at 22:48
  • I do not understand a question. You say custom and at very start continue with a well defined. Where is custom here? I do not understand a code either. Can you elaborate? – user14063792468 May 14 '22 at 22:52
  • The code is just an example of what I'm looking for might look like. This code wouldn't work if you just ran in in a web browser. – Some guy May 14 '22 at 22:55

1 Answers1

0

I feel like an easier way to add CSS to divs in JavaScript would be to use the .id or .classList.add functions.

JavaScript File:

//Creates the div
var div = document.createElement("div");
//Sets the text in the div
div.innerHTML = "Red Background";
//Applies Id and Class to the div
div.id = "customCSSId";
div.classList.add("containers");
//Adds the div to the html page
document.body.appendChild(div);

CSS File:

#customCSSId{
    width: 40px; 
    height: 40px; 
}
.containers {
    background: #f00;
}
Some guy
  • 148
  • 10
FairOPShotgun
  • 131
  • 2
  • 23