Wednesday, February 5, 2014

Most weird problem I have ever faced with JavaScript.

Recently I have faced a weird problem while working in a mobile web application. Application was built with HMTL/CSS/JavaScript. There was a screen where we were adding and removing HTML nodes dynamically with JavaScript. Here I have faced worst issue. When we remove HTML DIV node with JavaScript, it was still visible in DOM. Although it's removed but the DIV was still there. Although none of the events of DIV or Nodes inside DIV were working. There were few radio buttons inside it. If you tap on it, it does not work. That means elements are removed, but visually DIV was still there.

However it was working on other Android devices but was not working in Samsung Galaxy S4 with Android 4.3. It was not working in native internet application or Chrome in that device.

I was really surprised, as I have never faced such issue since I started working with JavaScript. And it's not a rocket science. Just the simple logic of removing the DIV with JavaScript and it did not work. See the code below.

var element = document.getElementById('modifier');
if(element){
          element.parentNode.removeChild(element);
}

As you can see, it's very simple code, first get element by id and remove it with parentNode. A standard JavaScript logic to remove HTML node. As we know it's  standard logic. W3Schools tutorial, also mention the same logic. Stack-overflow gives the same answer. Many JavaScript experts/bloggers have mentioned the same solution. But there was a issue, so how did I solve it.? See the code below.

var element = document.getElementById('modifier_');
if(element){
           var parentNode = element.parentNode;
           element.parentNode.removeChild(element);
           parentNode.innerHTML = parentNode.innerHTML;
}

This line  parentNode.innerHTML = parentNode.innerHTML does the magic. It's kind of refreshing the UI. It's really really stupid solution. But it solved this issue.

I don't know the reason why this issue was only on that device. So if you have any idea on this, please comment here. And if you ever encounter such issue, try using my solution.

No comments:

Post a Comment