JS function not working in Edge/IE11

I have the following code which works fine on most browsers. Unfortunately MS’s Edge and IE11 report a problem:

Object doesn’t support property or method ‘matches’

Is there a way I can get my function to work on Edge and IE11 or alternatively a way to detect if it’s an MS browser so I can revert to the non-JS fallback?

document
  .getElementById('clients')
  .addEventListener('click', function(event) {
    const target = event.target;
    
    if (!target.matches('[data-show]')) return; //here be the error

    hideAllA();
    recolorAllA();
    document
      .querySelector(target.dataset.show)
      .style
      .display = 'block';
    target.style.color = '#D74022';
  });

I can post a (non-)working page if necessary but I’d prefer not to unless it’s necessary…

Thx

Maybe an if else matchesSelector()

Or a polyfill

1 Like

Thanks, Mitt. matchesSelector gives me an error in my Chrome derivative.

Uncaught TypeError: target.matchesSelector is not a function

I’ll have to try the polyfill when I understand it…

Sorry, I should have pointed out that IE has an “ms” prefix. msMatchesSelector

1 Like

Yeah. I thought I would try your first suggestion (if I understood you correctly) and try matchesSelector() in place of matches() but it fails in Chrome, although webkitMatchesSelector() works, so it looks like a job for the polyfill.

I don’t know how you did your if else, but this hacked up version works (well, no error messages anyway) for me.

<!DOCTYPE HTML>
<html lang="en">
<head>
<title>matches() Testing</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<style type="text/css">
</style>
<script type="application/javascript">
// script needed before the DOM is loaded here
</script>
</head>
<body>
<h1>matches() Testing</h1>
<div id="clients" data-show="true" style="color: #00F">Clients</div>
  
<script type="application/javascript">
// script that needs the DOM to be loaded here
document
  .getElementById('clients')
  .addEventListener('click', function(event) {
    const target = event.target;
if(target.matches) {    
console.log('not IE');
    if (!target.matches('[data-show]')) return; //here be the error
} else if(target.msMatchesSelector) {
console.log('IE');
    if (!target.msMatchesSelector('[data-show]')) return; //here be the error
}
//    hideAllA();
//    recolorAllA();
    document
//      .querySelector(target.dataset.show)
      .querySelector('#' + target.id)
      .style
      .display = 'block';
    target.style.color = '#D74022';
  });
</script>
</body>
</html>

It’s safest just to say it wasn’t like that!!! I’ve been looking at the polyfill page and scratching my head, so many thanks for showing how to use it… :slight_smile:

Cool, that worked just perfectly. Thanks squire.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.