Ways to extract text solely from the parent element, excluding any content from the child elements

I need to extract just the text updated page title from the following code snippet

<h2 class="cmp-title__text" xpath="1">
            updated page title
        <span class="gmt_style" aria-hidden="true"&;gt;Tue, 20 Jul 2021 13:19:22 GMT</span></h2>

My current attempt is pulling the text from the span tag as well, resulting in Tue , 20 Jul 2021 13:!9:22 GMT.

var pgTitle=element(by.xpath("//h2[@class='cmp-title__text']"));
var pgTitleFromApp = await translatedPgTitle.getText();

output :

+updated page title
+Tue, 20 Jul 2021 14:02:35 GMT

Seeking assistance with this issue!

Answer №1

Xpaths for extracting text nodes from the provided html snippet:

<h2 class="cmp-title__text">
        updated page title
    <span>Tue, 20 Jul 2021 13:19:22 GMT</span>
    
    second text
    
    <span>Tue, 20 Jul 2021 13:19:22 GMT</span>
    
    third text
    
</h2>

Access the first text node using this xpath:

//h2[@class='cmp-title__text']/text()[1]

Retrieve the second text node using:

//h2[@class='cmp-title__text']/text()[2]

Text nodes not within a span parent:

//h2[@class='cmp-title__text']/descendant::text()[parent::*[name()!='span']]

Output (including whitespace):

     updated page title


second text



third text

First text node with span as parent:

//h2[@class='cmp-title__text']/descendant::text()[parent::*[name()='span']][1]

Equivalent xpath:

//span[1]/text()

Answer №2

To separate the strings obtained from the getText() function, you can try this method:

Here is an example:

var allWords = textFromFunction.split(' ');
var extractedTitle = allWords[0] + allWords[1] + allWords[2];

Answer №3

Here's a quick tip for handling text nodes in pure JavaScript:

If you're dealing with a situation where the text is always the first child, you can simply use the Node.firstChild method. However, if the text can be in any other position, you would need to use Node.childNodes to filter out the text nodes.

<div class="wrapper">
   Some text 1
   <h1>Some text 2</h2>
</div>
const wrapper = document.querySelector('.wrapper')
const parentTextNode = [...wrapper.childNodes]
   .filter(node => node.nodeType === Node.TEXT_NODE)[0];

console.log(parentTextNode); // Some text 1

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

Continue scrolling on the webpage that automatically loads new content

This code snippet has been my go-to for scrolling down dynamically loading webpages. delay_time = 3 # Get current scroll height last_height = driver.execute_script("return document.body.scrollHeight") while True: # Scroll to the bottom of t ...

What sets apart posting data through an HTML form submission from posting data through an Ajax request?

Recently, I've encountered an issue with my Post API. When calling it through AJAX, the user parameter is received but the StreamReader returns empty. [HttpPost] [Route("getUserBankList")] public IHttpActionResult getUserBankList(UserProfile ...

The importance of variables in Express Routing

I'm really diving into the intricacies of Express.js routing concepts. Here's an example that I've been pondering over: const routes = require('./routes'); const user = require('./routes/user'); const app = express(); a ...

Automatically append version number to requests to avoid browser caching with Gulp

When deploying my project, I utilize gulp to build the source files directly on the server. In order to avoid caching issues, a common practice is to add a unique number to the request URL as explained in this article: Preventing browser caching on web app ...

Encountering the issue of "Unknown provider" while injecting Angular modules

After following a tutorial on organizing an Angular project, I came up with a structure where I have a ng directory containing all my controllers, services, and the routes.js file. These are then bundled together into an app.js through my configuration in ...

Bootstrap 5.5.2 facing transition issues on bundle.js

Recently, I attempted to incorporate zoom.js into my project to enable image zoom functionality similar to that of the medium website. After linking both the CSS and JS files, it seemed to be working properly. However, I encountered an issue where the tra ...

"Transforming an array using the map method to generate an object containing arrays optimized for

I'm looking to extract an array of objects from a nested array within JS/React. I attempted the following approach, but it resulted in an error regarding react children - indicating that objects cannot be rendered as children and suggesting the use of ...

Shifting Angular Component Declarations to a New Location

Here's a question that might sound silly: In my Angular project, I am looking to reorganize my component declarations by moving them from angular.module.ts to modules/modules.modules.ts. The goal is to structure my src/app directory as follows: src ...

Tips for avoiding redundant AJAX requests

Currently, I am working with JavaScript and not jQuery. Imagine a scenario where I have 3 users in my database [Kim, Ted, Box] and 3 buttons structured as follows: <button class="user">Kim</button> <button class="user">Ted</button> ...

Learn how to display HTML content in trNgGrid using the $sce.trustAsHtml method

I am currently working with a table that has search options implemented using trNgGrid.js. The data for this table comes from a Sharepoint list where one of the columns contains HTML content that I need to display. To achieve this, I attempted using $sce. ...

Encountering a Peer dependency problem while executing node within a docker environment

Currently, I am utilizing `node-pg-migrate`, which has a peer dependency on `pg`. Here is an excerpt from the library's `package.json` file: "peerDependencies": { "pg": "^4.3.0" }, My attempt to execute the application in Docker involves the fo ...

Tips for incorporating broadcasting into my Angular application?

console.log('js'); var myApp = angular.module('myApp', ["ngRoute"]); myApp.config(function($routeProvider) { $routeProvider.when('/', { templateUrlnp: 'views/partials/logIn.html', controller: 'LoginC ...

Essential Input Element in HTML5

I'm currently facing an issue with form validation that involves two text boxes, both of which are optional. However, in order for the server to validate the form, one of the text boxes must be filled in. I have no problem with creating a required fie ...

Struggling with implementing conditional validators in Angular2 form models. I have tried using myForm.setValidators(), but it doesn't appear to be functioning as expected

I have been experimenting with the model form in an Ionic/Angular2 project. My goal is to implement conditional validation on a form where users initially fill out 6 required fields, and then choose between 'manual' and 'automatic' proc ...

"Use jQuery to target the first child element within a parent element that has a specific class

Is there a way to choose only the first child of a specific parent class with a certain class for the purpose of clone()? <div class="sector_order"> <div class="line_item_wrapper"> SELECT THIS DIV </div> <div class=" ...

JavaScript library called "Error: JSON input ended unexpectedly"

I am currently operating a server using node.js and Express v4.0 Additionally, I am utilizing the request library. However, when receiving a response from the server, I encounter an Uncaught SyntaxError: Unexpected end of JSON input. The response I receiv ...

Setting a default value within an input tag: A step-by-step guide

const [userData, setUserData] = useState([]); const handleUserInfo = (id) => { fetch(`https://602e7c2c4410730017c50b9d.mockapi.io/users/${id}`) .then(res => res.json()) .then(data => setUserData(data)) } <inpu ...

Similar Functionality to jQuery's .load() in REACT

I'm currently diving into the world of React, attempting to transition a PHP + jQuery Page to React (minus the jQuery). However, given the intricate complexity of the page, I won't be able to migrate everything at once. As a result, I need to sta ...

Looping through AJAX calls

Currently, I have a dataset that needs to be displayed on my webpage. Each item in the list has a unique identifier. Every item represents a bar and there is a corresponding document for bars that are visited by at least one user. If a bar has no visitors ...

Ways to navigate to a different page in React when a user clicks?

When working on my react app, I encountered an issue where the useHistory hook was undefined. How can I troubleshoot this problem and ensure that useHistory is properly defined? App.js import 'bootstrap/dist/css/bootstrap.css' import React f ...