Is it possible to manipulate DOM in node js?

Viewed 8498

I built a random quotes app using vanilla js and ajax and DOM manipulation and was wondering if I can do the js bit in the back end using node/express. However I can't seem to figure out if DOM manipulation ( like generating a new quote upon clicking the button ) can be done via NODE JS ?

5 Answers

You can parse HTML into a DOM with Node.js using a library such as libxmljs or cheerio which would then allow you to manipulate the result.

You can't use code running in Node.js to manipulate the DOM that a browser has built, or directly handle a click on a button rendered in the browser because both the button and DOM will be in the browser and not in the Node.js program.

The DOM is not part of JS. It is part of HTML, and as such requires the context of the browser in order for it to become available.

What you want to do is continue your DOM manipulation in the browser and make API calls to your node back end. This would be using something like the fetch API to broker the data and then responding to the data by updating the DOM appropriately for your application.

You can try to use some template rendering language like (ejs, handlebars...) to use your vanilla javascript code.

There are many template engine manipulation you can use to generate server side rendering your page. With template engines you can serve html and manipulate the DOM before serving to the client.

You need distinguish what's dom and what's node firstly.

1.DOM

Means to be running in browser, it's need three type files

  • js
  • css
  • html

2.Node

It's a programing language, a tool, looks like javascript. You can't running node in brsower. But you can create html/css/js file by node coding, alse you can return them by server framework (eg. node express)

3.My suggestion

If you truely wanna write some code in node express, and do some DOM manipulate. try:

  • SSR (Server Side Render)
  • Coding your DOM code in ejs file or some other server side html template
  • Return your page by writing server api(Express is good choice to do that)

Well, here Node/Express is a backend tool and your browser (where vanilla JS would run) is a front end.

A backend can generate output in the form of HTML/JSON/XML or even plain text!. But similarly, as we can't change the value returned by a function, The backend cannot change once it outputs something.

Here the frontend tools are used, that are able to change the DOM which is vanilla JS in your case.

So one way is fetching a new resource from backend all together OR the smarter way is to just fetch the quote you want to change (by creating a REST API on the same backend)

so you need some route like /page/quotes that return an HTML page

and some route like /api/random_quote that may return a random quote in JSON format. that you may call from frontend JS using something like fetch

Related