1. What are the roles of 'name' and 'id' attributes in HTML tags? What is an appropriate use of both?
Name and Id attribute is used to get the required element from the document.
< input type="text" name="email" id=”txtEmail”/>
Id attribute accepts unique values, which can be used to identify the element from the document by using getElementById method
var vObjEmail = document.getElementById(“txtEmail”);
Name specifies the name of an element. Document.getElementsByName can be used to get elements with the specified names.
By using getElementById & getElementsByName, we can avoid traversing across intermediate nodes and hard coding paths.
2. Which pointers does each node in the DOM tree typically have?
Each element on the HTML page is considered as node in the DOM tree.
Each node has parentNode and childNode property. Using parentNode parent object of node is obtained and using childNode, array of child nodes is obtained.
3. Given a node object from a DOM tree, how do we determine if it is a text node or a regular node?
nodeName property gives information about the node’s type. By checking the nodeName property of a node, we can determine if it’s a text node or regular node.
If the nodeName property is “#text”,it is text node.
4. Why is it better to use either trickling or bubbling of events? Why not just give the event to the node on which it was invoked?
Suppose there is element inside an element and both have click events. And the click event of element 2 is fired first then click event of element1 is called event bubbling. And reverse is click event of element 1 is fired then click event of element 2 is called event capturing.
We can decide whether to register event handler in capturing or bubbling phase. This is done through addEventListener() method
element1.addEventListener('click',doSomething2,true)
element2.addEventListener('click',doSomething,false)
If the last argument is true, event is set to capturing phase, if false it is set to bubbling phase.
5. Can you think of one situation where you would want to prevent the browser from submitting a form after a user has clicked on the 'submit' button? How would you achieve this?
Suppose there are some validations that must be satisfied before submitting data to server. In that case, we can validate data using JavaScript on button click, if all validation is done then save data otherwise return from the function.
This is done by using “return false” or event.preventDefault(); which will stop further propagation of events.