How to retrieve an array of positions for a particular element using PhantomJS

Seeking the positions of a specific tag on a webpage using PhantomJS, such as <a> tags, and aiming to obtain an array like this one:

[
   {
       tag: "a",
       x: 12,
       y: 32,
       width: 100,
       height: 30
   },
   ...
]

The code I have written is as follows:

page.open(url, function(status){
   ....
   ....
   var a_tags = page.evaluate(function() {
                     return document.getElementsByTagName('a');
                });

   for(index in a_tags){
      console.log(a_tags[index].getBoundingClientRect());
   }
   ....
   ....
})

However, running this code leads to the following error:

TypeError: null is not a function (evaluating 'a_tags[index].getBoundingClientRect()')

I am seeking guidance on how to retrieve this information from a webpage using PhantomJS and what might be causing the issue with my current code?

Answer №1

This is the resolution that worked for me :

let all_a_tags = page.evaluate(function() {
      let tags = document.getElementsByTagName('a');
      let results = [];
      for(let index = 0 ; index < tags.length ; index++) {
          let element = tags[index];
          let rectangle = element.getBoundingClientRect();
          if(rectangle.left == 0 && rectangle.top == 0 || rectangle.width == 0 && rectangle.height == 0){
                     continue;
          }
          results.push({
                tag: "a",
                rect: rectangle,
          });
      }
      return results;
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Next.js build process encountered an error when building due to an issue with plotly.js (The build failed with a ReferenceError: self is

Whenever I attempt to build the Next.js app for production using the yarn build command, I encounter the following error. Strangely enough, everything works perfectly fine on the development server when using the yarn dev command. The app employs the react ...

Link Array with Google Charts

I've been struggling for a long time to connect this array to a Google chart with no success. I would really appreciate some assistance in identifying what mistake I've made. I have created a jsfiddle where the array appears to be correct, and wh ...

Angular is displaying the main view two times instead of loading the appropriate template

I've encountered a perplexing issue with Angular templating - instead of loading the correct template, the main view is rendered twice. Despite investing a considerable amount of time over the past 48 hours attempting to resolve this issue, I have mad ...

Using environmental variables in Nuxt 2 or Nuxt 3 - a step-by-step guide

I have an .env file located in the root of my project. In my nuxt config, I am using variables to configure ReCaptcha as shown below: import dotenv from 'dotenv' dotenv.config() export default { modules: [ ['@nuxtjs/recaptcha&ap ...

I am attempting to use $.map to transfer values into a new array, but unfortunately, it is not producing the desired result

This task seems easy at first glance, but unfortunately it's not working for me. Can someone please point out what I might be doing wrong? var oldArr = [0, 1, 2]; var newArr = []; /* * This function is supposed to add 1 to each element in the array ...

Troubleshooting: Issues with updating a text field in Vue test utils using Jest

Hello, I am new to Jest and unit testing. I have a question about how to set the value of a text input using Vue Test Utils. Here is the code for my custom text input component: <input v-model="local_value" @keyup.enter="submitTo ...

Implement a mechanism for updating a child property whenever the parent state changes

In my setup, there's a parent state that includes a 'Theme' state. Current layout looks like this: The Parent Component holds the state of Theme. The Parent component passes down the current state to the child component as a "theme" prop ...

The AJAX request fails to execute once the webpage has finished loading for the first time

Hey there! I have a button group where the selected button triggers an ajax call. Check out the code below: <div class="btn-group" id="graphSelection"> <button type="button" class="btn disabled btn-info" id="post" onclick="graphSelec ...

What is the best way to eliminate properties from multiple objects that are not undefined?

When attempting to remove properties from an object, it may throw an error if the property does not have a value. What is the correct method to delete similar properties from multiple objects? Main.js if (data.details.primary.transactionHistory !== undef ...

jQuery "ooze navigation" - precise pixel rounding

After successfully programming my jQuery slime menu, I am facing a minor issue. Although the menu works beautifully, I have noticed that when I move the arrow and the ending circle of the slime separately, they do not always connect accurately if the curso ...

The dropdown list is not getting populated with data retrieved from an HTTP response

My experience with making HTTP calls is limited, and I am facing an issue while trying to populate specific properties of each object into a dropdown. Despite attempting various methods, such as using a for loop, the dropdown remains empty. created(){ a ...

Check for mobile browser without having to refresh the page

Currently, I am facing an issue with closing the sidebar when the user clicks on Click Me button in mobile view using flexbox layout. The problem arises because the page needs to be refreshed for it to recognize if it's in mobile mode or not by utiliz ...

What causes the .getJSON function to return a MIME type error when trying to access the API

I've been attempting to make a call to the Forismatic API, but I keep encountering a MIME type error when sending it. JQuery Request: $(document).ready(function() { $("#quote-button").on("click", function(){ $.getJSON("https://api.forism ...

I am trying to create a mailto link using jQuery, but I am unsure of how to open the link in a new tab (_blank)

On my webpage, there is a hyperlink: <a id="contact" href="#">contact</a> In my jQuery code, I have the following: $("#contact").click(function() { document.location.href = "mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_ema ...

Exploring the contents of an array

I am attempting to use weatherapi for obtaining forecast data and my goal is to access the hourly forecast in order to display the time and condition text for each hour object within a react component. However, I have been struggling to figure out how to r ...

How do I overwrite this calculation using JQuery?

I have a website: link There are two pages on my site that have the same div elements... I want one page to perform a certain calculation on the divs, and another page to perform a different calculation... New JavaScript Code: jQuery(document).ready(fu ...

Tips for creating a functional null option using the select ng-options feature

While there are a few questions and answers on this topic, I have yet to find a solution that works for my specific case. Imagine having an object like this: $scope.person = {name: 'Peter', category1: null, category2: null}; Another variable r ...

Issue specifically with Android 6 WebView - jQuery 1.9.1 where a RangeError is thrown due to the call stack size being exceeded

An error message "Uncaught RangeError Maximum call stack size exceeded" is causing a web application to fail in the jQuery-1.9.1 extend() function, but strangely it only occurs on Android 6. The application runs smoothly on all other platforms such as Des ...

Obtaining a file from Firestore using cloud functions

I have experimented with various approaches, like: const admin = require("firebase-admin"); admin.initializeApp(); const db = admin.firestore(); const docRef = db.collection("users").doc(dynamicDocID).get() const docRef = db.collectio ...

Difficulty with rendering speed when reusing a directive in AngularJS

Here is a basic directive called "base": angular.module("base", []) .directive("base", function() { return { restrict: "A", scope: true, controller: function($scope) { this.setHeader = function(header) { $scope.h ...