Home > Blockchain >  Jquery node.js returning empty HTMLImageElement
Jquery node.js returning empty HTMLImageElement

Time:07-22

I'm trying to use jquery on node.js to edit each image size (width) on a string variable, But when i run the script, jquery returns to me an empty HTMLImageElement object

Why?

Here is my node.js code:

var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;

var $ = jQuery = require('jquery')(window);

var HTML = `<p><img alt="2SolGivenWeForSo,WeWeV₁ifFromلية{I NodeneedaboveFromCircuitNumberHerehaveVzrequireqov toisabovei=" src="https://media.cheggcdn.com/coop/bdc/bdcaa47c-5ae3-4694-a53f-c4310faf5ba6/1658405118815_Net_1.jpg" style="height:3360px;width:1940px"><img alt="ApplyWeSo,R↓!Nodal↑analysisI, t Iz t Iz = 0.have,From17I,   I   Iz1₁₂-02T2015I,   I₂   I3 = 0.I₁   (14  15)" src="https://media.cheggcdn.com/coop/450/45080cff-9a57-4bc0-a09c-e29a88de45d4/1658405138263_CamScanner07-21-202217.33_1.jpg" style="height:3176px;width:1844px"><img alt="V₁Substitue1111FromThe介-From- 716V₁N₁ - V₂16- 7V₂N₂V₁₂ - V₂ =NSubstitue162-NolauationValue21642" src="https://media.cheggcdn.com/coop/2ba/2bac1f60-655a-4aa4-a2ae-37703cd7903f/1658405154236_Net_3.jpg" style="height:3164px;width:1824px"></p>`

$('img', HTML).each(
    function() {
        // var w = $(this).attr('width').match(/\d /);
        // var percent = (w / 2);
        // $(this).removeAttr('width').css('width', percent   'px');
        console.log(this)
    });

After running the code, the console logs:

HTMLImageElement {}
HTMLImageElement {}
HTMLImageElement {}

CodePudding user response:

I think you need to pass the HTML variable when you create the new JSDOM instance.

var HTML = `<p><img alt="2SolGivenWeForSo,WeWeV₁ifFromلية{I NodeneedaboveFromCircuitNumberHerehaveVzrequireqov toisabovei=" src="https://media.cheggcdn.com/coop/bdc/bdcaa47c-5ae3-4694-a53f-c4310faf5ba6/1658405118815_Net_1.jpg" style="height:3360px;width:1940px"><img alt="ApplyWeSo,R↓!Nodal↑analysisI, t Iz t Iz = 0.have,From17I,   I   Iz1₁₂-02T2015I,   I₂   I3 = 0.I₁   (14  15)" src="https://media.cheggcdn.com/coop/450/45080cff-9a57-4bc0-a09c-e29a88de45d4/1658405138263_CamScanner07-21-202217.33_1.jpg" style="height:3176px;width:1844px"><img alt="V₁Substitue1111FromThe介-From- 716V₁N₁ - V₂16- 7V₂N₂V₁₂ - V₂ =NSubstitue162-NolauationValue21642" src="https://media.cheggcdn.com/coop/2ba/2bac1f60-655a-4aa4-a2ae-37703cd7903f/1658405154236_Net_3.jpg" style="height:3164px;width:1824px"></p>`
const { JSDOM } = require( 'jsdom' );
const jsdom = new JSDOM( HTML );

// Set window and document from jsdom
const { window } = jsdom;
const { document } = window;
// Also set global window and document before requiring jQuery
global.window = window;
global.document = document;

const $ = global.jQuery = require( 'jquery' );

const img = $( 'img' );
console.log( img.length )
  • Related