Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Element with id or class with React Dom

I am creating an element like so

const foo = document.createElement('div');
ReactDOM.render(component, foo);

I wonder if it is possible to create foo with an class or id?

like image 576
Stophface Avatar asked Mar 08 '26 15:03

Stophface


2 Answers

I would suggest you create it in a proper React way:

const App = () => {
  return React.createElement(
    "div",
    {style:{color:"red"}, id: 'someId', className: "someClass"},
    "Here I am",
  );
};

ReactDOM.render(React.createElement(App), document.getElementById("root"));
like image 139
Lazar Nikolic Avatar answered Mar 10 '26 04:03

Lazar Nikolic


The id and/or class of foo can be specified via the setAttribute(..) and classList.add(..) methods as shown:

const foo = document.createElement('div');

/* Set id of "some-id" on foo */
foo.setAttribute("id", "some-id");

/* Add class of "some-class" to foo */
foo.classList.add("some-class");
like image 31
Dacre Denny Avatar answered Mar 10 '26 03:03

Dacre Denny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!