简体   繁体   中英

Test DOM methods in javascript IDE not in browser console

I am wondering why when using any IDE that support javascript language if you try to get element of HTML page using document.querySelectorAll() or any DOM selector method it will return run time error ReferenceError: document is not defined ?

is the reason that document only defined in browser javascript build in console ?

my problem that I only need to run javascript app on my IDE not on browser console to test it.

if there is any suggested solution please mention it.

What do you mean by run "on my IDE" ?

I think you rather talking about rendering on server side.

Either way, yeah the document exist solely on the browser, if nothing is done to mock it. but there are solutions to mock the document, for example, jsdom :

https://github.com/tmpvar/jsdom

It is useful for example for running unit tests on server side, without browser, to test UI components which require DOM and have some logic.

Finally solution that worked in my case using Nodejs , jQuery and jsdom library as suggested in jony89's answer .

in newer jsdom v10 API I should parse my HTML page into JSDOM constructor to get the result that I expected.

but it's difficult and inconvenient to pass the whole HTML page to JSDOM constructor so I used another simpler way to solve it using older jsdom API and exactly by jsdom.env() method :

https://github.com/tmpvar/jsdom/blob/master/lib/old-api.md

I pass the page url that I want to use DOM methods on it and then print the output on my nodejs IDE:

var jsdom = require("jsdom/lib/old-api.js");

jsdom.env(
    "http://www.ammanu.edu.jo/English/Research/Research.aspx",
    ["http://code.jquery.com/jquery.js"],
    function (err, window) {
        var $ =  window.$;
        var a = $("section a");
        for(var i = 0; i < a.length; i++){
           console.log(a[i].getAttribute("href"));
        }
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM