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);
}
});