Loading...

Children of The DOM in Javascript

View: 359    Dowload: 0   Comment: 0   Post by: hanhga   Category: Javascript   Fields: Other

Close node relationships in the DOM have always been problematic, because most interpretations of theDOM include whitespace text-nodes, which scripts don’t usually care about.

It’s right that they should be included, of course, because it’s not up to implementations to decide whether this or that node is important. Nevertheless, whitespace text-nodes are usually not important, they just get in the way, complicating what should be simple relationships like firstChild and nextSibling.

Here’s a simple markup example to demonstrate:

<ul>
  <li>list-item 1</li>
  <li>list-item 2</li>
  <li>list-item 3</li>
</ul>

So the firstChild of that <ul> element is not the first <li> element, it’s the whitespace (i.e. the line-break and tab) between the <ul> and <li> tags. Likewise, the nextSibling of that first list-item is not the second list-item, it’s the whitespace text-node in-between.

The Classic Solution

This is nothing new, and traditionally we’ve had three basic ways of dealing with it. The first is to use a collection-based reference like this:

var item = list.getElementsByTagName('li')[0];

The second approach is to iterate past the unwanted nodes, using a nodeType test to determine when we have the node we want:

var item = list.firstChild;
while(item.nodeType != 1)
{
  item = item.nextSibling;
}

The third and most brute-force solution is simply to remove the unwanted nodes altogether, using a recursive function like this (which also removes comment nodes):

function clean(element)
{
  for(var x = 0; x < element.childNodes.length; x ++)
  {
    var child = element.childNodes[x];
    if(child.nodeType == 8 
      || (child.nodeType == 3 && !/S/.test(child.nodeValue)))
    {
      element.removeChild(element.childNodes[x --]);
    }
    if(child.nodeType == 1)
    {
      clean(child);
    }
  }
}

The Element Traversal Solution

These solutions all work, but there is a much simpler and eaiser way of getting the elements references we want, using a suprisingly little-known set of references defined in DOM3 Element Traversal.

The Element Traversal specification defines four new references, which only relate to element nodes, effectively ignoring all other types:

firstElementChild

lastElementChild

nextElementSibling

previousElementSibling

So now we can get those list-item references in a much more straightforward way, and it doesn’t matter how many whitespace text-nodes (or anything else) are in-between:

var item = list.firstElementChild;
var item2 = item.nextElementSibling;

The specification also defines a childElementCount property, which is equivalent tochildNodes.length when all non-element nodes are disregarded.

The Real-World Solution?

So can we rely on these properties, will they work in the browsers we code for? The answer is “yes” for the most part. Older versions of IE are the usual story, but for IE9 or later, or any reasonably-recent version of any other major browser, we find that all these properties are supported, and have been for quite a while.

PPK’s DOM Compatibility tables give us the low-down, and show that we don’t need to worry at all about lack of browser support — unless we have to support IE8.

So I guess it’s one of those things, just like selector queries used to be — if older browsers are an issue, then libraries can provide the fallback, or you can continue to use the traditional solutions we’ve always relied on. But if you’re lucky enough not to have to think about those older browsers, then the Element Traversal properties will certainly make life easier.

I could also point out that earlier versions of IE have a different view of the DOM — unlike all other browsers, they don’t include whitespace text-nodes. So at a pinch, you could always do something like this:

function firstChild(element)
{
  //using pre-defined browser variable
  if(isie)
  {
    return element.firstChild;
  }
  return element.firstElementChild;
}

A browser test is appropriate for that, rather than simply testing whether firstElementChild is defined, because lack of support for that property doesn’t necessarily indicate an implementation where whitespace isn’t included. The difference is unique to IE, so it’s IE we’d have to test for.

The Common-Sense DOM

To me, these Element Traversal properties are something a breeze of common-sense in W3Cspecifications — ratifying in standards the practical view that most of have of the DOM. They’re certainly a lot more approachable than DOM2 Traversal ever was (anyone here using TreeWalker? No, I didn’t think so!). The underlying problem that DOM Traversal tried to solve, is that implementations can’t know which types of node a script will care about, yet it tried to solve this problem by continuing to treat all types of node as equal.

Children of The DOM in Javascript

Close node relationships in the DOM have always been problematic, because most interpretations of theDOM include whitespace text-nodes, which scripts don’t usually care about.

Posted on 09-04-2016 

Comment:

To comment you must be logged in members.

Files with category

  • Mini Youtube Using ReactJS

    Mini Youtube Using ReactJS

    View: 25    Download: 2   Comment: 0

    Category: Javascript     Fields: none

    This is one the best starter for ReactJS. MiniYoutube as the name suggests is a youtube like website developed using reactJS and youtube API. This project actually let's you search , play and list youtube videos. Do check it out and start learning...

  • Angular 6 Starter with Laravel 5.6 API Service

    Angular 6 Starter with Laravel 5.6 API Service

    View: 62    Download: 0   Comment: 0

    Category: Javascript     Fields: none

    Angular 6 and Laravel 5.6 This project is a starter for creating interface with Angular using bootstrap && css && sass and using Laravel 5.6 for api requests. Demo Installation This project is divided in two parts (projects) and before use them you...

  • Simple Richtext Editor Based on pellJS

    Simple Richtext Editor Based on pellJS

    View: 26    Download: 0   Comment: 0

    Category: Javascript     Fields: none

    A simple visual editor for websites using the pell javascipt. It also has the option to switch between visual editor mode and source code mode. I will upload an update for new functionality soon. Source Code Editor Visual Editor

  • Data Visualization for BI: How to Design Layouts for .NET Financial Reports

    Data Visualization for BI: How to Design Layouts for .NET Financial Reports

    View: 37    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    With the Active Reports Server, you can have a multi-tenant environment where users from various departments, companies, or other specifications can log in, view their reports (and only their reports), export the data, or set up a distribution...

  • AngularJS and REST API

    AngularJS and REST API

    View: 204    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    This is a tutorial for those interested in a quick introduction to AngularJS and REST API. We will build the familiar Periodic Table of the Elements found in every chemistry textbook, and allow the user to select a Chemical Element by clicking on...

  • Collective Intelligence, Recommending Items Based on Similar Users' Taste

    Collective Intelligence, Recommending Items Based on Similar Users' Taste

    View: 168    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Using Collaborative Filtering to find people who share tastes, and for making automatic recommendations based on things that other people like.

  • Think Like a Bird for Better Parallel Programming

    Think Like a Bird for Better Parallel Programming

    View: 157    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Coding an application to run in parallel is hard, right? I mean, it must be hard or we’d see parallel programs everywhere. All we'd see are slick parallel apps that use every available core effortlessly. Instead multi-threaded apps are the exception...

  • Getting Started with the Bing Search APIs

    Getting Started with the Bing Search APIs

    View: 169    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Bing Search API is a set of REST interfaces that find web pages, news, images, videos, entities, related searches, spelling corrections, and more in response to queries from any programming language that can generate a web request. Applications that...

 
File suggestion for you
Loading...
File top downloads
Loading...
Loading...
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd