4

I would like to check if element is visible in DOM in Node.js. I use jsdom library for getting DOM structure. There are 2 approaches how to check element's visibility in client side javascript, but it doesn't work with jsdom in node.js.

1) offsetParent property is always null, even for visible elements

2) dom.window.getComputedStyle(el).display returns block, but element's css rule is display: none

const request = require('request');
const jsdom = require("jsdom");
const { JSDOM } = jsdom;

request({ 'https://crooked.com/podcast-series/majority-54/', jar: true }, function (e, r, b) {
  const dom = new JSDOM(b);
  test(dom);
});

const test = (dom) => {
  const hiddenElement = dom.window.document.querySelector('.search-outer-lg');
  const visibleElement = dom.window.document.querySelector('.body-tag-inner');
  console.log(dom.window.getComputedStyle(hiddenElement).display); // block
  console.log(visibleElement.offsetParent); // null
}

Is it possible or another way how to check element's visibility in DOM in node.js?

Matt
  • 8,195
  • 31
  • 115
  • 225
  • Can you check if you have access the `hidden` property? See: https://github.com/jsdom/jsdom#pretending-to-be-a-visual-browser – k0pernikus Sep 05 '19 at 09:37
  • @k0pernikus thanks for reply. I think, I have access to `hidden` property. `dom.window.document.hidden` returns `true`. I tried to create dom structure with `pretendToBeVisual: true` option and `dom.window.document.hidden` returns `false` but it didn't change anything. – Matt Sep 05 '19 at 09:46

3 Answers3

3

I tried puppeteer instead of jsdom and I got correct display value. Here is the snippet:

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

  await page.goto(uri);

  const searchDiv = await page.evaluate(() => {
    const btn = document.querySelector('.search-outer-lg');
    return getComputedStyle(btn).display;
  });

  console.log(searchDiv)
  await browser.close()
})()
Matt
  • 8,195
  • 31
  • 115
  • 225
2

Trick method :)



function isHiddenElement(selector) {
    return (document.querySelector(selector).offsetParent === null)
}

if(isHiddenElement('.search-outer-lg')
{
  alert("element hidden");

}


dılo sürücü
  • 3,821
  • 1
  • 26
  • 28
-1

try without use

const  a1=dom.window.document.querySelector('.search-outer-lg');
  const coponentStyle= dom.window.getComputedStyle(a1)
  coponentStyle.getPropertyValue('display')
[![const  offsetParet=window.document.querySelector('.body-tag-inner').offsetParent][1]][1]

it return body hav class archive tax-podcast_type term-majority-54 term-98

// it will be return none itry this in the consle without use dom show this imageshow this image if it not work tell me

Mohammed Al-Reai
  • 2,344
  • 14
  • 18
  • I believe this works in client side javascript, but my question is for back-end javascript in node.js – Matt Sep 08 '19 at 11:59