• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

116
Views
How to store a reference to another element on a jquery parent element

I'm constructing some DOM elements on the page and want to keep a reference to a child element on the parent for updates later

    for(i = 0; i < itemList.length; i++) {
            const item = $(`<div></div>`);
            item.addClass('List_Item');

            item.title = $(`<div></div>`).addClass('List_Title');
            item.append(item.title);

            $(item).init.prototype.getName = function() {
              return $(this).data('name');
            }
            
            $(item).init.prototype.setName = function(name) {
              $(this).data('name', name);
              $(this).find('.List_Title').text(name);
            }
            
            item.setName(sources[i].name);
    }

How can I avoid using .find() in this manner to grab the child element with a selector and instead keep a reference to it on the item element itself?

Edit:

I've opted for a function saved to a .data() store

            item.data('name', sources[i].name);
            
            var getName = function() {
              return item.data('name');
            }

            var setName = function(name) {
              item.data('name', name);
              title.text(name);
            }
            item.data('setName', setName);

I can then access this externally later like so

          $('.List_Item').each(function(index, item) {
            if($(item).data('name') == prevName) {
              var setName = $(item).data('setName');
              setName(newName);
            }
          });
about 3 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error