Link to home
Start Free TrialLog in
Avatar of MJ
MJFlag for United States of America

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:
<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>

Open in new window

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

Open in new window

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
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MJ

ASKER

Thank you very much!
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;
}

Open in new window

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

Open in new window