How to get parent element's attribute from event in IE 11?

Viewed 865

I have following , which works in chrome and other browsers but not in IE 11. I'm not sure which part of this code IE doesn't support. In all the other browsers i get svgimageclicked in console log but get an error in IE:

unable to get property 'getAttribute" of undefined or null reference

<div id='content' data-attribute="svgimageclicked"> 
  <svg .......
</div>

document.getElementById('content')
  .addEventListener('click', this.handle_click.bind(this));

handle_click(event){
   console.log(event.target.parentElement.getAttribute('data-attribute'); 
}
2 Answers

try this example:

var el = event.target.parentElement;
var v = getAttribute(el, "data-attribute");

function getAttribute (dom, attr) {
            if (dom.getAttribute !== undefined) {
                return dom.getAttribute(attr);
            } else if (dom[attr] !== undefined) {
                return dom[attr];
            } else if (dom.getAttributeNode !== undefined) {
                return dom.getAttributeNode(attr);
            }else{
                  return null;
            }
        }

I tried to test your code and found that it is giving an error in other browsers too.

I suggest try to refer to an example below will work with the most of the browsers including the IE browser.

<!doctype html>
<html>
   <head>
   </head>
   <body>
      <div  id='content' data-attribute="svgimageclicked">
         <svg height="100" width="100">
            <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
            Sorry, your browser does not support inline SVG.  
         </svg>
      </div>
      <script>
         document.getElementById('content').addEventListener('click', handle_click);
         
         function handle_click(event)
         {  
            var target = event.currentTarget;
                        var parent = target.parentElement.nodeName;
                console.log(target.getAttribute('data-attribute')); 
         }  
          
      </script>
   </body>
</html>

Output in the IE 11 browser:

enter image description here

Related