MJ
asked on
JavaScript - Isolate Specific Element to Attach Listener?
I had the following code that worked but now the web-app has changed and there re multiple "btn-grp-back" on the page. Here is the "Edit" link element:
Thanks!
<div class="row btn-row-group"><button type="button" class="btn btn-mobile btn-tertiary btn-grp-back mt-5" data-name="btn-grp-back">Edit</button></div>
and here is the previously working code:
function _dtmCheckFundingEditLink() {
editLink = document.querySelectorAll('.btn-grp-back');
if (editLink != null) {
editLink[2].addEventListener('click', _dtmGetCurrentFundingAmount, false)
} else {
setTimeout(_dtmCheckFundingEditLink, 1000);
}
};
So my question is what is the best way to target this specific element and add the event listener to it? Using the index " editLink[2]" is not stable.Thanks!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Just for interest sake - while being a bit more verbose this code is about 2-3x faster than the XPath solution. (Also works on IE - not sure if the XPath functionality is available on IE)
function getElementByClassAndContent(cls, cnt) {
var els = document.querySelectorAll(cls);
var found = false;
for(var k in els) {
if (els[k].textContent === cnt) {
found = els[k];
break;
}
}
return found;
}
If you are prepared to go to ES6 then you can get it down to the following with a slight performance gain
function getElementByClassAndContentES6(cls, cnt) {
return [...document.querySelectorAll(cls)].find(item => item.textContent === cnt);
}
ASKER