Chapter 5. JavaScript and Directly Accessing the User Interface
The user interface in JavaScript applications is typically the web page in which the script is embedded. The page may open in an Android tablet or a traditional computer browser, but the concepts are the same.
Nowadays, most people use libraries and frameworks in order to manipulate the web page. However, no matter how helpful and sophisticated the library, you still need to have a good idea of what you can, and cannot, do to the web page before making effective use of a library. More importantly, you need to have a good idea of the best practices to use when modifying the web page.
Accessing a Given Element and Finding Its Parent and Child Elements
Problem
You want to access a specific web page element, and then find its parent and child elements.
Solution
Give the element a unique identifier:
<divid="demodiv"><p>This is text.</p></div>
Use document.getElementById() to get a reference to the specific element:
vardemodiv=document.getElementById("demodiv");
Find its parent via the parentNode property:
varparent=demodiv.parentNode;
Find its children via the childNodes property:
varchildren=demodiv.childNodes;
Discussion
A web document is organized like an upside-down tree, with the topmost element at the root and all other elements branching out beneath. Except for the root element (HTML), each element has a parent node, and all of the elements are accessible via the document.
There are several different techniques available ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access