Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

59
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);
            }
          });
7 months ago ยท Juan Pablo Isaza
Answer question
Find remote jobs