Struggling to effectively use XPath to target LI elements that contain specific text

Below is the HTML code for the list item in question:

<li class="disabled-result" data-option-array-index="1" style="">4" (0)</li>

Here is my attempt at using JavaScript to hide this list item, but it's not working as expected:

var xpath = "li[contains(.,'4"')]";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
matchingElement.setAttribute('style', 'display: none;" ) !important' );

Ideally, I would prefer to assign an ID to the specific list item I want to hide, but due to constraints with this being a Wordpress website, that method is not feasible.

An observation worth noting is that the <li> element does not appear in the page source, only in the inspector. The JavaScript code is placed in the footer of the page.

Any assistance on this matter would be highly appreciated as I have been struggling to find a solution.

(I also attempted the code without the var matchingElement declaration. My knowledge of XPath is still limited, as I am more accustomed to using querySelector.)

Edit: Included below is the complete code for the <UL>

<ul class="chosen-results">
<li class="active-result result-selected" data-option-array-index="0" style="">Size</li>
<li class="disabled-result" data-option-array-index="1" style="">4" (0)</li>
<li class="disabled-result" data-option-array-index="2" style="">5" (0)</li>
<li class="active-result" data-option-array-index="3" style="">Extra Large (5)</li>
<li class="active-result" data-option-array-index="4" style="">Large (7)</li>
<li class="active-result" data-option-array-index="5" style="">Medium (8)</li>
<li class="disabled-result" data-option-array-index="6" style="">Small (0)</li>
</ul>

Answer №1

To solve this issue, consider implementing the code provided below:

const xpathQuery = "//li[contains(text(), '4\"')]";
const matchingElement = document.evaluate(xpathQuery, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
matchingElement.setAttribute('style', 'display: none;" ) !important' );

If that doesn't work, you can give this code a shot as well:

const xpathQuery = "//li[@class = 'disabled-result' and contains(text(), '4\"')]"

Answer №2

Not entirely certain if this will resolve the remaining code issues, but it's important to include "//" at the beginning of your xpath. Testing your xpath in firebug or chrome's elements dom would provide clarity on this matter.

var xpath = "//li[contains(.,'4"')]";

//Make sure to use double quotes like this.

var xpath = "//li[contains(.,'4\"')]";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
matchingElement.setAttribute('style', 'display: none;" ) !important' );

//The following code effectively removes the intended element.

<ul class="chosen-results">
<li class="active-result result-selected" data-option-array-index="0" style="">Size</li>
<li class="disabled-result" data-option-array-index="1" style="">4" (0)</li>
<li class="disabled-result" data-option-array-index="2" style="">5" (0)</li>
<li class="active-result" data-option-array-index="3" style="">Extra Large (5)</li>
<li class="active-result" data-option-array-index="4" style="">Large (7)</li>
<li class="active-result" data-option-array-index="5" style="">Medium (8)</li>
<li class="disabled-result" data-option-array-index="6" style="">Small (0)</li>
</ul>

<script type="text/javascript">
var xpath = "//li[contains(.,'4\"')]";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
matchingElement.setAttribute('style', 'display: none !important;')
</script>

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

Delving into the World of ES6 Symbols

Throughout my experience with various programming languages, from C# to Lisp to Scala to Haskell, symbols have consistently behaved as singleton objects. This means that any two symbols with the same name are guaranteed to be identical. In Racket: (equal? ...

Mastering advanced String templating using loops and control statements in Javascript

During runtime, I receive an array similar to the example below: var colors = ['red', 'green', 'blue']; I then need to create a JSON String that looks like this: { "color" : { "name" : "foo", "properties ...

How can VueJs effectively update the data fetched using the created function?

When working with the Promise Object, I prefer to utilize the "then" and "catch" functions instead of asynchronous functions for handling responses in a simpler way. This allows me to avoid using await and conditional if-else statements to check the stat ...

How is it possible that this React setter is effectively working despite the fact that it is within a stale closure

I've come across this interesting function that I need help understanding. The randomize function seems to be consistent in its behavior despite multiple renders, thanks to being wrapped in a useCallback. Each time the randomize button is clicked, it ...

What are the different ways to position div containers using CSS?

So I have multiple div sections on my webpage, and they are arranged vertically in the following manner: However, I would like them to appear more like this: This is the structure of my HTML: <div id="main"> <div id="header"> ...

Unable to input new data into the fields within the text box

I am facing an issue while trying to input new fields in the Origin Place section of a Flight search application at . Despite attempting various XPath and locators, I am unable to successfully input any new information. The default value in Origin Place p ...

Using string replacement for effective search finding: Unleashing the power of substring matching

I have a method that adds an anchor tag for each instance of @something. The anchor tag links to a specific sub URL. Check out the code: private createAnchors(text: string) { return text.replace(/(@[^ @]+)/ig, '<a href="/home/user/$1">$1& ...

Utilizing getStaticProps for Performance Optimization in Next.js

I am currently in the process of setting up a blog using Next.js and GraphCMS. I have an ArticleList component that I want to display on multiple pages, such as my homepage and under each article as a recommendation. Since the article list is sourced from ...

Having trouble adding global method using Plugin in Vue 3?

I have been working on creating a method that can generate local image URLs to be used in any template automatically. However, I encountered an issue while trying to develop a plugin that adds a global property. Plugin Implementation: // src/plugins/urlb ...

Challenges regarding variable scope in JavaScript

Presented below is the JavaScript code I am currently using, which involves jQuery: function language(language) { var text = new Object(); $.ajax({ type: "GET", url: "includes/xml/languages/" + language + ".xml", dataType: ...

What steps can be taken to resolve the mouse-pointer problem?

Currently, I am utilizing PHP, jQuery, JavaScript, and other tools for my website development. I have a new requirement for a script in jQuery/JavaScript that can trigger an alert when the user's mouse-pointer moves away from the tab where my website ...

Having trouble navigating the dependency graph: Unable to locate module './crypto_auth' in sodium-universal

Encountering the following error while trying to browserify a node project from https://github.com/datproject/sdk: Error: Can't walk dependency graph: Cannot find module './crypto_auth' from 'C:\myPath\node_modules\sodium ...

Avoid refreshing the page upon pressing the back button in AngularJS

Currently, I am working on building a web application that heavily relies on AJAX with AngularJS. One issue I am facing is that when the user clicks the back button on their browser, the requests are being re-made which results in data having to be reloa ...

Include an option for whitespace characters when validating a file using regex

My text box has specific criteria for what is considered good or bad input. Examples of good input could include: GoodString GoodString88 99GoodString I want to avoid certain types of bad input, such as: Good*String Good&String However, I do want ...

How can the dot badge in Material-UI be enlarged?

I'm in need of a badge component that serves as an indicator without displaying any values. I opted for the dot variant, but it's too small for my liking. I tried modifying it with CSS, but it doesn't seem to be working as expected. Any sugg ...

How to bring in images from a local source in a React.js file

I've been looking into relative paths and absolute paths, but I'm having trouble importing local images correctly. My main objective is to create a React slideshow using these images. Why does it keep trying to find the images in the "components" ...

Tips for executing an SQL query containing a period in its name using JavaScript and Node.JS for an Alexa application

Hello there, I've been attempting to make Alexa announce the outcomes of an SQOL query, but I'm encountering a persistent error whenever I try to incorporate owner.name in the output. this.t("CASEINFO",resp.records[0]._fields.casenumber, resp.r ...

Customizing upload directories in elfinder for dynamic path generation

In my CodeIgniter project, I am trying to configure elfinder to have a dynamic upload path for each unique ID. The folder structure I am working with is as follows: Below are my elfinder settings: $idce = $_GET['id_c']; $client_code = $this- ...

Reposition the div element on mobile devices using media queries

Hello, I'm facing an issue on mobile with my website: dev site Today, I implemented a dropdown menu with flags to allow language switching. However, the dropdown in mobile is appearing under the hamburger nav bar. I was thinking of using media querie ...

How can I configure Express to act as a pass-through proxy server?

How can I set up an express server to act as a proxy? Requirements: Support for both http and https Ability to function behind a corporate proxy Option to provide custom content for specific URLs I have experimented with various modules such as http-pr ...