Tag Archive for: DOM

Tracking changes in the DOM

Check input using HTML5 and MDL

You can use input’s attributes as min, max, pattern and so on, and then checking a simple class do what you need to. In this example we are using a Text Field component of  Material Design Lite (MDL) which shows a message and a red mark up when the value is not the right one. You could extend this with as many inputs as you like and then if all of them are correct show a login button or whatever.

Note that in old browsers and android versions before Lolipop where the Web View isn’t Chrome you will need to use directly Validation DOM Methods. Ex:

document.querySelector('input').validity.rangeOverflow

Be careful because even some Validation DOM Methods are not well supported in old browsers versions.

createDocumentFragment vs innerHTML

DOM access takes a lot of time, you should think about this every time you are programming and optimize your code avoiding unnecessary access.

  • If you are going to insert a bunch/list of elements in the DOM and you want to show/insert them one by one, use createDocumentFragment, it’s the fastest way.
  • If you want to show/insert them all when they are ready, at the same time, use innerHTML, in this case it will be faster even than createDocumentFragment.

Never use innerHTML when you want to render one by one, it’s the slowest one (DOM access + creation).

If you want test it for your own and see the timing, run the code below with num: 10, 100, 500, 1500.

Which is the different between property and attribute?

A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.

HTML Attributes

Syntax:

<body onload="foo()">

DOM Properties

Syntax:

document.body.onload = foo;

Using jQuery

If we have:

<!-- HTML -->
<input class-gns="brand">
// jQuery
$("input").attr("data-gns"); // return "brand"
$("input").prop("data-gns"); // return "undefined" because it is not in the DOM.
// It's trying to get [HTMLInputElement].data-gns

See a real example: