Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

i'm trying to get elements by id from an html file in a js file using nodejs. I'm getting the error 'document id not defined' because node doesn't provide a document object model by default.

So how can i use document.getElementById() in nodejs ?

Thank you !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
412 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you want to parse files within the same server you should probably use some of this options, because nodejs it's just a JavaScript implementation, There is no window or document object, see this. But to answer exactly your question:

how can I use document.getElementById() in nodejs ?

You could do it using Puppeteer

Puppeteer is a Node library which provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol. It can also be configured to use full (non-headless) Chrome or Chromium.

Here a basic example:

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();


        page = await browser.newPage();
        await page.goto('http://example.com/some.html', {waitUntil: 'load'});


    const newPage = await page.evaluate(() => {

        return  document.getElementById("idexample").innerHTML;

        });

     console.log(newPage)

  })();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...