1

I'm using the following code to get all img tags inside a page:

"use strict";
var system = require('system');
var args = system.args;
var page = require('webpage').create();

page.onLoadStarted = function () {
    console.log('Loading Page...');
};

page.onLoadFinished = function (status) {
  console.log('Loading finished.');
  var imgs = page.evaluate(function() {
    console.log(document.images);
    console.log(document.images.length);
    return document.images;
    });
  for (var i = 0; i < imgs.length; i++){
    //console.log(JSON.stringify(imgs[i]));
    console.log(imgs[i]);
    console.log(imgs[i].alt);
    }
  phantom.exit();
};

page.open(system.args[1]);

It outputs the alt text correctly as expected, but on the line:

console.log(imgs[i]);

It only outputs: "[object object]" I would expect to get all of the img tag code, if i use JSON.stringify it outputs an immensely long msg that is also not the img tag code as I want.

Can anyone explain what is going on? How am I supossed to get the img tag code?

2
  • 1
    console.log(imgs[i].outerHTML); Commented Apr 20, 2016 at 16:51
  • @AndréDion that was it, thank you. Feel free to post it as an answer. Commented Apr 20, 2016 at 16:56

1 Answer 1

5

What's going on? Not sure to be honest. I suspect you're comparing PhantomJS's handling of logging an Element object with Chrome's JS Console which displays a live reference as the tag instead of [Object object]. If you were to alert(imgs[i]) from Chrome you'd see [Object HTMLImageElement].

You'll get what you want from console.log(imgs[i].outerHTML);.

See Element.outerHTML.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.