Querying with CSS or XPath Selectors

Have a query for our CSS & Xpath Selector experts - I managed to extract text using XPATH but struggling with a CSS Selector,

Here's the scenario:

<span class="piggy">
    <i class="fa fa-try"></i>
    <strong>euros (€) !</strong>
270,38K</span>

I can easily obtain "270,38K" using XPATH,

document.evaluate('//*[@id="wrap"]/span/text()', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent.trim();

Output -> 270,38K (success)

However, I'm unable to do so with a CSS Selector,

document.querySelector('span.piggy').innerText.trim();

Output -> euros (€) ! 270,38K (incorrect)

Can anyone help me retrieve only the text value of span (excluding children content) using a css selector?

Appreciate your assistance!

Answer №1

While your selector is correct, you may need to do a bit of additional work to retrieve the text node containing the desired information since it cannot be accessed through a CSS selector alone.

To obtain the text content, you can retrieve the last child node, which should be a text node, from the element by using lastNode and accessing the textContent property.

document.querySelector('span.piggy').lastNode.textContent

Alternatively, you can use the childNodes list as shown below:

let nodes = document.querySelector('span.piggy').childNodes;
console.log( nodes[nodes.length-1].textContent );

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

Looking for someone to break down this Typescript code snippet for me

As a Javascript developer, I am currently diving into an unfamiliar TypeScript code block within a project. Here is the code snippet: ViewModel newPropertyAddress = new ViewModel(){name, previousPro = oldValue } ...

What distinguishes reference types from primitive types like boolean and numbers?

Is it true that we have the option to define numbers like this: const num = 10; Or can we only use this way of declaration: let num = new Number(10); I'm curious if I am limited to the first variation for declaring numbers. ...

Styling an input button to look like a link in Firefox and Internet Explorer

I'm currently using CSS to give my input button the appearance of a link. Here's how I've styled it: input#linkLike { background: none; border: none; cursor: pointer; margin: 0; padding: 0; text-decoration: none; ...

Implement a cron job in Node.js to automatically trigger an Express route on a weekly basis

I need to run tests on a certain page every week by creating a cron job that will access my express route at regular intervals. Currently, I have set up a cron job to run every 2 minutes as a test: //schedule job every 2 minutes schedule.scheduleJob("* /2 ...

`The function `setTimeout` throws an error when passed as a string.`

Here are two pieces of code that may look identical, but one works properly: function hideElement(obj) {setTimeout(function() {obj.style.display = "none";}, 20);} On the other hand, the second one results in error: obj is not defined: function hideEleme ...

mobile navigation menu remains open after selecting a link

When the Fixed-to-top navbar is used in mobile view, such as clicking a Navbar icon, it does not collapse afterward while the page is loading. How can I prevent the page from loading in the navbar section? Here is the link to my website: CLICK HERE Addi ...

The package.json could not be parsed due to an error

I am currently facing an issue while trying to deploy a JavaScript Node.js project on Heroku. Everything works fine on localhost, but upon uploading, I encounter an "unable to parse" error at : ... "engines" : { "node" : ">0.11.9" }, ... The Error Mes ...

Struggle with connecting to Firebase database

I've been grappling with errors while trying to build a list of users using Firebase's collection feature. https://i.sstatic.net/BTPMM.png I've provided the information I'm inputting below: https://i.sstatic.net/yVD0i.png This is my ...

Adding supplementary documents within the app.asar file via electron

This is a Vue application using electron-builder. { "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "electron:build": "vue-cli-service electron:build", "electron:serve": "vue-cli-service electron:serve", ...

What is the most optimal jQuery code to use?

Just wondering, which of the following code snippets is more efficient (or if neither, what would be the best way to approach this)? Background - I am working on creating a small image carousel and the code in question pertains to the controls (previous, ...

What is the best way to split key and value into separate array objects using JavaScript?

Here's a snippet of code I am working with: let obj = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'} var years = []; let i; for (i= obj;i<=obj;i++) { years.push({ edad_beneficiario : i }) } When I run this code, the output i ...

`How can textures be added to the front and back of a shape in Three.js geometry?`

I'm currently working on creating a flat shape geometry with rounded corners. Below is a snippet of the code I have so far: var geometry = new THREE.ShapeGeometry(shape); var front_material = new THREE.MeshPhongMaterial({ map: frontTexture, s ...

Using Selenium in Java, one can wait for a JavaScript event (such as onchange) to finish before proceeding

When a group of interconnected input fields have an onchange event, the values in some fields are updated correctly while others are not due to interference from the onchange event. Once the onchange event is triggered on a field, it initiates a process t ...

Using Angular Material to create tabs and grid lists (md-tabs and md-grid-list

I'm having trouble getting the md-grid-list to appear inside an md-tab. I copied the md-grid-list code from here and placed it under a series of dynamically generated tabs. However, the grid list doesn't seem to be displaying on any of the tabs ...

String creation from HTMLDivElement

Is it possible to create a string from a JavaScript HTMLElement Object? Here's an example: var day = document.createElement("div"); day.className = "day"; day.textContent = "Random Text"; If we have created the day HTMLDivElement Object, can we make ...

Unique Title: "Tailored Scrolling Method with Dynamic Flicker

I created a scroll animation function for transitioning to the next div. It works smoothly in Firefox, but I am experiencing flickering issues in Chrome when scrolling multiple times. Here is a fiddle Check out the code snippet below: var mousewheelevt ...

At what point does angular2 @output get resolved?

Click on this link Here is the HTML code snippet: <chart [options]="options" (load)="saveGraphInstance($event.context)"></chart> <div (click)="switchGraph()">switch</div> <div (click)="showLoadingForce()">show loadin ...

Difficulties with choosing predecessors

Is there a way in the HTML snippet below to extract the checkall from the thing? .. <input type="checkbox" class="checkall"><label>Check all</label> <ul> <li><input type="checkbox" class="thing"><label>Thing 1 ...

Tips on implementing a function within a navigation bar from a specific context

While working with a user authenticated context, I encountered an issue with the logout function. My goal is to have a link in the navigation bar that triggers the logout function and redirects me to the home page. However, I'm receiving a Typerror: l ...

A step-by-step guide on integrating HTML form input with an API object array

I'm looking to combine two code "snippets" but I'm not sure how to do it. One part of the code turns HTML form input into a JSON object. You can see the CodePen example here. What I want is when the "Add note" button is clicked, I want to grab ...