RegEx in JavaScript to identify and match the innerHTML property of all elements

I am currently in the process of developing a Chrome extension that needs to identify specific pages within a website, including the Log In / Sign In page, the Sign Up / Register page, the About page, and the Contact Us page.

My approach involves obtaining a list of elements on the page, which I have already accomplished. Now, I need to examine the innerHTML of each element to ensure it is a leaf node in the DOM and contains a portion of the keyword. I am attempting to accomplish this using a regex. Although I have successfully created a regex that extracts content between start or end tags of an element, it does not capture the innerHTML. Below is my progress so far, focusing on the About page:

var list = document.body.getElementsByTagName("*");
var aboutElement = /^[^<.+>].*About.*[^(<.+>]$/i;

for (var i = 0; i <= list.length; i++) {
    if ((aboutElement.test(list[i].innerHTML)) || (aboutElement.test(list[i].alt))) {
        list[i].click();
    }
}

I am seeking guidance on how to modify the regex pattern to only match leaf nodes (nodes without child nodes) and avoid capturing content within start or end tags. I suspect that the current regex pattern may match everything in the innerHTML due to the .* section, so adjustments might be necessary. Any assistance or suggestions would be highly appreciated!

Answer №1

Big shoutout to the helpful suggestions in the comments that steered me towards solving the issue. By utilizing the .textContent method and making adjustments to the regex as detailed below, I was able to successfully resolve the problem at hand.

var elements = document.body.getElementsByTagName("*");
var targetElement = /^(.*?\s*(\bTarget\b)[^$]*)$/i;

for (var j = 0; j <= elements.length; j++) {
    if ((targetElement.test(elements[j].textContent)) || (targetElement.test(elements[j].alt))) {
        elements[j].click();
    }
}

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

Node.js powered file uploading on the Heroku platform

After attempting to upload a file to Heroku using https://www.npmjs.com/package/express-fileupload, I encountered an error. It worked fine on my PC, but on Heroku, I received the following error message: {"errno":-2,"code":"ENOENT","syscall":"open","path" ...

How can I retrieve the parent scope in an Angular UI nested named view?

One of the challenges I faced in my application was dealing with nested views within several screens. After experimenting with different approaches, I discovered that creating modal dialog boxes and sliding panels as actual nested states with corresponding ...

Eliminating the Skewed Appearance of Text in Input Fields Using CSS

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Customized Page Layout</title> <script src="https://c ...

Is it possible to enhance an external class with a non-static method using prototypes?

Is it possible to use prototypes to add a function for a class instance? allowing me to access this or __proto__ keyword inside my method, like so: class PersonClass { name: string; constructor(name: string) { this.name = name; } sayHello() ...

I created a customized version of jQuery tabs, but I am looking for an external link to display the tab content and to style the original navigation

I've been experimenting with modifying a tabs script in jQuery that I came across. It seems like my attempt to enhance it has made things more complex than necessary. While I know creating tabs with jQuery is simple, I wanted to create my own version ...

One required positional argument is needed in `update_one()`: 'update' is missing

I've exhausted all possible options, but I can't seem to make it work. Any suggestions on how I can get this code to function properly? I attempted using ajax_data to update the values, but it was unsuccessful. The main goal of this code is to al ...

Using the hover event in a jQuery plugin: A step-by-step guide

A star rating plugin I am developing is encountering an issue with implementing the hover event. jquery, (function($){ $.fn.extend({ rater: function(options) { var defaults = { } var options = $.exten ...

Aligning images with absolute CSS to text that is wrapping positions the images perfectly alongside the text content

My webpage has a long content section that resizes based on the browser width. Here's an example: <h1 id="loc1">Title</h1> <p>bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bod ...

The FormData object appears to be blank, even though it was supposed to be populated when attempting to send a PDF file using a multipart FormData POST request in Cypress

I am attempting to send a PDF file as a POST request. The API supports the use of @RequestPart and @RequestParam: @RequestPart("file") MultipartFile file; @RequestParam(value = "document-types", required = false) Set<String> documentTypes; My appro ...

Adding click functionality to dynamically generated list items in jQuery and HTML

I'm encountering an issue while trying to assign click events to dynamically added HTML elements in jQuery. Despite extensive research within this community, I find myself more confused than before. Below is the snippet of code causing me trouble: v ...

Jquery Query: Is it possible to incorporate variables into CSS properties?

I manage a website that supports multiple languages, and I want to adjust the position of my container based on the selected language. To achieve this, I attempted the following code: prop = lang == 'ar' ? 'right' : 'left'; $ ...

JQuery isn't functioning properly on dynamically generated divs from JavaScript

I'm currently tackling an assignment as part of my learning journey with The Odin Project. You can check it out here: Despite creating the divs using JavaScript or jQuery as specified in the project requirements, I am unable to get jQuery's .hov ...

Utilizing Firebase's real-time database for executing specific conditional queries

I am currently utilizing Express along with the Firebase Realtime Database Admin SDK to handle my database operations. My goal is to retrieve all tickets with a status of pending or open that belong to the logged-in user. However, I am facing difficulty in ...

What is the correct syntax for comparing -1, 0, and 1 in JavaScript?

Is there a way to achieve the functionality of a <=> b in JavaScript? It seems that this operator does not exist. Any suggestions for an equivalent function? Appreciate it, Dorian ...

Initiate Ant Design select reset

I am facing an issue with 2 <Select> elements. The values in the second one depend on the selection made in the first one. However, when I change the selected item in the first select, the available options in the second one update. But if a selectio ...

Adding Firebase Authentication to my AngularJS website

I am currently creating a school website using AngularJS. My goal is to incorporate account functionality through firebase authentication. However, I have limited experience with Javascript and find working with AngularJS and implementing firebase to be ...

Wildcard for keys in JavaScript objects and JSON

I have a JSON object that contains specific key-value pairs, and I am attempting to manipulate strings based on this object. Here is an example of the JSON structure: { "foo %s": "bar %s", "Hello %s world %s.": "W ...

What is the best way to retrieve all the listed TV and film ratings in descending order? Using Django

Our Goal I aim to organize movies based on their star ratings and filter out those with ratings lower than a specified threshold. 2. Retrieve the IDs of Movies and TV shows mentioned in the view, fetch the data and score through URLs one by one. 3. Presen ...

JQuery class for swapping elements upon scrolling

I am currently working on a navigation bar that changes classes to create a fading effect for the background. The approach I have taken involves targeting the window itself and monitoring the scroll position of the user. If the user scrolls down more than ...

Load information into a different entity

I need help with adding new values to an existing object. When I receive some form data from noteValue, I also have additional input data in my component under person that I would like to integrate into noteValue before saving it. let noteValue = form.va ...