Having trouble accessing the text in a paragraph using JavaScript executor and web driver

On a particular website, there is:

<p id="tempid" value="Manual Effect">testing the test</p>
String value = (String)((JavascriptExecutor) this).executeScript("return window.document.getElementById('tempid').value");
System.out.println("value is : " + value);

Currently, I am receiving a null value or nothing.
I am looking to obtain the text "testing the test" as my desired output.

Answer №1

Avoid using Javascript as mentioned by others. WebDriver is not necessary if you do.

WebElement textElement = driver.findElement(By.id("tempid"));
String content = textElement.getText(); //this line will give you "testing the test"
String attributeValue = textElement.getAttribute("value"); //this line will give you "Manual Effect"

Answer №2

https://i.sstatic.net/gE7Qc.png

Dear Sir,

I would like to suggest trying out this solution...

String script = "return document.getElementsByTag('p').tempid.getInnerHTML()";

String script1 = "return document.getElementByID('tempid').innerHTML;

JavaScriptExecutor js = (JavaScriptExecutor)driver;

String result = (String)js.executeScript(script);

System.out.println(result);

JavascriptExecutor is more advantageous than webdriver in many aspects. WebDriver operates on the basis of webElements, and sometimes if a webElement is not accessible, it can lead to StaleElementExceptions or ElementNotFoundExceptions... which can be quite a headache.

On the other hand, JavaScript Executor works directly with HTML, making it a preferable option.

Answer №3

(String) ((JavascriptExecutor) this)
                    .executeScript("grab the innerHTML content of an element with the id 'tempid' from window.document");

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

Converting a JSON String into a Map

Recently, I have come across a JSON value that looks like the example below and I am looking for advice on how to efficiently parse and extract the pair values of data from it, especially in Java using the org.json library. { "columns" : [ "Book", " ...

Encountering a constructor problem while Jest is mocking a class from an NPM module

I'm currently attempting to create a mock for the Discord.JS module. Within this module, there is a Client class that I am extending in my own "Bot" class. My goal is to mock the module in order to simulate certain methods on other classes such as "Me ...

Most effective method for waiting for a dropdown to load and choosing a value using Selenium in JavaScript

My current task involves interacting with a website built in React using Selenium to choose a value from a dropdown menu. Given that the website is built in React, I understand that waiting for the DOM to be ready may not always work as expected, but I st ...

Transferring information from jQuery to AngularJS controller

Is there a way to transfer data generated by jQuery into an AngularJS controller? <textarea ng-click="showSelectedText(selection.text)" name="editor1" id="editor1" cols="118" rows="35"> Using jQuery to collect data: $( "#editor1" ).select(funct ...

Leveraging real-time geographical location data for a weather widget with OpenWeatherAPI integration

My goal is to incorporate the current geolocation feature into a weather widget that I am developing. At the moment, I can only show data from cities based on an external source. My coding knowledge is quite limited. I am not a professional in this field, ...

Safari is not properly handling element IDs when used in conjunction with React

I am currently in the process of building a straightforward single-page website utilizing React. At the top of the page, there is a navigation bar that contains links to various sections of the site: <li><a href="/#about">About u ...

Error message: "Unexpected token" encountered while using the three.js GLTFLoader() function

I have a requirement to load a .glb model into three.js by using the GLTFLoader. I was able to successfully create a rotating 3D mesh on a canvas without encountering any errors in the console. However, when I tried to replace it with the .glb model, I enc ...

ng-model to interact with dynamically loaded elements

My dynamic list contains various items, such as cars, and is not of fixed length. Upon loading, the list appears as follows: itemList = [ { id: 0, name: 'bmw' }, { id: 1, name: 'audi' }, { id: 3, name: 'vw' }, ...

What could be the reason that my Javascript function is not displaying in the HTML document?

I'm currently working on developing an HTML page that displays random quotes by Mark Twain. The function and array of quotes are set up in a separate Javascript file which is linked to the main HTML document. However, I am facing an issue where the ou ...

React.js Form Validation issue: When using input type "number", the text field remains a single value even after attempting to delete characters with the backspace key

Experiencing difficulty in clearing the input field value, even after pressing backspace the value remains constant. One particular value persists in the input field. import * as React from "react"; import { Button, Form } from "react-boots ...

I am having trouble understanding why my GraphQL query is not retrieving any data from the WordPress GraphQL API when using SWR

I have created a query to retrieve my WordPress navigation menus using the WordPress graphql plugin along with swr, graphql, graphql-request, and next.js on my local files. When I add the query on the wp-grphql section of my site, I am able to successfully ...

Tips for solving the "jQuery needs a window with a document" error when using import statements

I'm encountering the "jQuery requires a window with a document" error, and it appears that I require guidance similar to this solution: Error: jQuery requires a window with a document My quest is to find the precise syntax for addressing this using i ...

Merging Data with mongoDB

Just starting out with MongoDB, I have developed an app that functions similar to Twitter with followers and following. Here is the schema I am working with: UserSchema : username:'Alex', pass:'salted', likes:'200&ap ...

Typescript's way of mocking fetch for testing purposes

I have a query regarding the following code snippet: import useCountry from './useCountry'; import { renderHook } from '@testing-library/react-hooks'; import { enableFetchMocks } from 'jest-fetch-mock'; enableFetchMocks(); i ...

Having Trouble Using Fetch API with ASP.NET Core 2 Controllers that Require Authorization

I have the following code on the client side: fetch("/music/index", { headers: { "Content-Type": "application/json" } }) .then(response => { if (!response.ok) { throw response; } return response.json(); }) ...

Performing an Axios POST request in a React Native and React app using JSON.stringify and Blob functionality

I am currently developing an application where I have encountered an issue when calling an API endpoint in react native. Interestingly, the web app (built with React) does not encounter any errors. Here is the code for the web app using React with TypeScri ...

Timestamped console output in Eclipse

Currently working with Selenium webdriver scripts in Eclipse, and I am looking for ways to display console output with timestamps. Even though I am utilizing the log4j framework for application logging, my client specifically requires console output with t ...

Dates comparison causing Firestore security rules issue

After running the query shown below, I encountered a permission-denied message with an error in the "Monitor rules" tab. const timeNow = useMemo(() => Timestamp.now(), []); const query = query( postRef, where("tags", "array-contai ...

React Sentry Error: Attempting to access properties of undefined object (reading 'componentStack')

Utilizing the ErrorBoundry component from Sentry in my react project has been a goal of mine. I aim to confine the errors reported to Sentry specifically for my React app, as it is deployed on multiple websites and I want to avoid picking up every JS error ...

Four unique chip/tag colors, personalized to suit your style

Currently, I have integrated two arrays into my autocomplete menu where the chip/tag color is either primary or secondary based on the array the selected component belongs to. I aim to include all four arrays in the menu (top10Songs, top10Artists, top10Fi ...