Using getElementByID with dynamically generated IDs

I need to extract data from a website for my job using a Chrome bookmarklet. Unfortunately, I don't have permission to modify the site's code.

Here's an example of the type of field I want to extract:

<div style="width:100%; height:100%;" bindonce="" class="ng-scope">
    <de-field-label>
        <div class="pull-left ng-scope" style="width: 100%">
            <label class="pull-left">Last Name</label>
        </div>
    </de-field-label>

    <input class="tt-input ng-scope"
           bo-class="{'tt-agency-required': field.agencyValidation === 1}" 
           de-cascade=""
           ng-disabled="true"
           de-input-mask=""
           de-text-box=""
           sectionid="0b340920-8989-ce72-7bb4-08d51598a6d9-0" 
           id="Victims_0b340920-8989-ce72-7bb4-08d51598a6d9_0_lastName"
           disabled="disabled">
</div>

The id is dynamically generated

Answer №1

One way to target specific elements based on their id is by using the attribute selector. You can check if the id starts with a certain string like 'Victims_' with the following code:

document.querySelector('[id^=Victims_]')

Similarly, you can also look for elements whose id ends with a specific string (e.g., 'lastName') using the following code:

document.querySelector('[id$=lastName]')

Answer №2

If you're unable to determine the ID in advance, relying on getElementById won't be of much help.

Look for other characteristics of the element that can serve as unique identifiers, such as a class, a data-* attribute, or its position within the DOM relative to an element with a known ID. Essentially, anything that can be targeted using a selector.

Subsequently, utilize this information as an input for querySelector.

Answer №3

It seems that the IDs are constantly changing, requiring a different approach to identify the input and retrieve the ID value. Here is one way to achieve this:

var input = document.getElementsByClassName("tt-input").item(0);
var id = input.id

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

Error in Express Session: Property 'signin' is not found in type 'Session & Partial<SessionData>'. Code: 2339

I received the following Error Code: Property 'signin' does not exist on type 'Session & Partial<SessionData>'. (2339) About My Application src/index.ts import "reflect-metadata"; import express = require("expr ...

Encountering a CORS issue specifically on the client side of a Next.js application when interacting with an API gateway

I've been struggling with this issue for a week now and can't seem to fully describe it. I have a FastAPI server running as a Lambda connected to API Gateway. https://i.stack.imgur.com/S5Zx9.png Both FastAPI and API Gateway have CORS enabled, b ...

Can you pinpoint the issue with this asynchronous function in Vue3?

Dealing with a simple concept error, I find myself unable to solve it. Within the onMounted hook, everything looks correct - an Array of three objects is displayed. However, when I return it to the template and try to interpolate it, all I see is an empty ...

Tips for managing Material-ui's <Autocomplete/> component based on the option's id

When dealing with HTML select in React, it's common to use an id or key to keep track of the selected value: <select value={value} onChange={(event) => setValue(event.target.value)}> {options.map((option) => ( <option value={optio ...

Ways to choose a designated element without relying on ids or classes

I am looking to create an on-click function for each button, so I require a method to select each one individually without relying on IDs <div class="col"> <div> <b>Name:</b> <span ...

Knex is requesting the installation of sqlite3, but I am actually utilizing a MySQL database

While attempting to execute a query on my local MySQL database using knex, I encountered an issue where it prompted me to install the SQLite3 driver, even though my database is MySQL. To troubleshoot, I installed the SQLite3 driver to see if it would reso ...

The art of controlling iframe elements with jquery

I've been researching various topics related to this issue, but I'm still unable to achieve the desired outcome. Currently, I am embedding an iframe within an HTML document like so: <iframe class="full-screen-preview__frame" id="nitseditpre ...

Instead of returning a JSON result, the MVC controller method called from AngularJS is returning the view HTML

Within the HomeController, I have the following method, [HttpGet] public ActionResult GetStudents() { Student std1 = new Student(); List<Student> stdlst = new List<Student>(); std1.Id = 1; ...

Tips for identifying the correct selectedIndex with multiple select elements present on one page

How can I maintain the correct selectedIndex of an HTMLSelectElement while having multiple select elements in a loop without any IDs? I am dynamically loading forms on a webpage, each containing a select element with a list of priorities. Each priority is ...

It appears that the query parameters are impacting the speed at which the page loads

I am currently developing a project on this platform. It is using c9.io, an innovative browser-based collaborative programming IDE. The index.php file includes the following script: <?php $path = ltrim($_SERVER['REQUEST_URI'], '/&ap ...

Preventing Click Events during Data Fetching in React.js without Using jQuery

In the redux store, there is a state called isFetching. When data is being fetched from the backend, this state becomes true. I need to disable all click events when isFetching is true, without using jQuery. I stumbled upon some solutions (involving jQuer ...

"Encountering a problem with numerous callbacks in the getJSON method

I am working on creating marker pop ups that display information from different ajax requests on a map. In order to make the second call, I utilize an userID obtained from the first call. While the information from the second call is displayed correctly, ...

Tips for globally overriding MUIv4 class in JSS for nested themes

Summary: Skip to EDIT2 MUIv4 has generated the following classes for me based on my nested theming: <label class="MuiFormLabel-root-121 MuiInputLabel-root-113 MuiInputLabel-formControl-115 MuiInputLabel-animated-118 MuiInputLabel-shrink-117 M ...

What is the best method to ensure that none of the select option values are left empty?

I have a total of 5 select option drop down menus currently, but this number may increase in the future depending on requirements. The issue I'm facing is that when I select the last element, it returns true even though the other elements are empty. I ...

Is it possible to eliminate the dedupe feature in npm?

By mistake, I accidentally ran the command npm dedupe and now all of my node_modules directories are flattened. While this reduces file size, it's making it more difficult to find things. Is there a way to reverse this and return to the hierarchical f ...

Deleting a nested object from an array within another object

Recently, I delved into the world of Redux and have found it quite fascinating. However, I am currently facing a dilemma where my new reducer function inadvertently changes the type of a state variable, which is not what I intended. The desired structure ...

Encountering an error while trying to run the command "npm run start" due to an issue of "EMFILE

After running npm update, my project start broke. When I try to use npm run start, it returns the following error: 10% building 0/1 entries 0/0 dependencies 0/0 modulesnode:internal/errors:484 ErrorCaptureStackTrace(err); ^ Error: EMFILE: too many ...

jquery to create a fading effect for individual list items

I have a group of items listed, and I would like them to smoothly fade out while the next one fades in seamlessly. Below is the code I've been working on: document.ready(function(){ var list_slideshow = $("#site_slideshow_inner_text"); ...

jQuery - Event cannot be triggered on the 'deselect' or 'focusout' of <option> tag

Check out the demo here Hello there, I have a situation where I need an input box to appear below a select option, only if the user selects "Other". The code currently uses the .click() function on the option, but now I am trying to make the input box di ...

button to dim the image collection

On the top right corner of my image gallery, there's a button that, when clicked, creates an overlay darkening the image. I'm trying to figure out how to toggle this effect on and off with a click. Any suggestions on how I can achieve this? Here ...