Wrapper Classes In Java

Wrapper Classes:

Wrapper classes were introduced with the discussion of the primitive data types. Primitive values in Java are not  objects. In order to manipulate these values as objects, the java.lang package provides a wrapper class for each of the primitive data  types. All wrapper classes are final. The objects of all wrapper classes that can be instantiated are immutable, that is, their state cannot be  changed.

Although the Void class is considered a wrapper class, it does not wrap any primitive value and is not instantiable. It just denotes the Class object representing the keyword void.

In addition to the methods defined for constructing and manipulating objects of primitive values, the wrapper classes also define useful  constants, fields, and conversion methods.

When working with numbers, most of the time you use the primitive types in your code. For example:

int i = 500;
float gpa = 3.65f;
byte mask = 0xff;

There are, however, reasons to use objects in place of primitives, and the Java platform provides wrapper classes for each of the primitive data types. These classes “wrap” the primitive in an object. Often, the wrapping is done by the compiler—if you use a primitive where an object is expected, the compiler boxes the primitive in its wrapper class for you. Similarly, if you use a number object when a primitive is expected, the compiler unboxes the object for you.

All of the numeric wrapper classes are subclasses of the abstract class Number:

ammar

Primitive class 

int
char
float
boolean

Wrapper class coreesonding to their respective primitives 

Integer
Charecter
Float
Boolean

Example:

if(Character.isDigit(a[i]))
System.out.println(a[i] + “is a digit “);
if(Character.isLetter(a[i]))
System.out.println(a[i] + “is a letter “);

Byte class methods:

byteValue() – returns the Byte value as byte value
Ex : byte bvalue = Byte.byteValue();
parseByte() – returns byte value from a byte string
Ex: byte bvaue = Byte.parseByte(“93”);

Integer class methods:

intValue() – returns the Integer value as int value
Ex: int bvalue = Integer.intValue();
parseInt() – returns int value from a int string
Ex: int bvaue = Integer.parseInt(“73”);

Usage of Wrapper Classes:

They should be used in situations when primitives cannot be used. The main situation is when you want to store primitives in one of the Java collections (which cannot handle primitives).

The use of the wrapper classes is greatly simplified by something called autoboxing. This means that Java automatically determines whether a primitive or a corresponding wrapper should be used. So it’s rare that you need to use the wrapper classes explicitly.

Example:

ArrayList<Integer> al = new ArrayList<Integer>();

Integer is the wrapper for int. Thanks to autoboxing you can now store ints in the above Arraylist. Or rather Java will perform all necessary conversions back and forth between Integer and int.

Reason of using Wrapper Classes:

1) It is sometimes easier to deal with primitives as objects.
2) Moreover most of the collection classes store objects and not primitive data types.
3) The wrapper classes provide many utility methods also.
Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.

Exception Throwing Principles

Exception handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or exceptional events requiring special processing – often changing the normal flow of program execution. It is provided by specialized programminglanguage constructs or computer hardware mechanisms.

In general, an exception is handled (resolved) by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an exception handler. If exceptions are continuable, the handler may later resume the execution at the original location using the saved information. For example, a floating point divide by zero exception will typically, by default, allow the program to be resumed, while an out of memory condition might not be resolvable transparently.

Alternative approaches to exception handling in software are error checking, which maintains normal program flow with later explicit checks for contingencies reported using special return values or some auxiliary global variable such as C’s errno or floating point status flags; or input validation to preemptively filter exceptional cases.

            Throwing an Exception:

Various exceptions are thrown at the bytecode or system level, such as when an integer division by zero is attempted, when an attempt is made to access an invalid array index, or when Java’s object allocator runs out of heap memory. However, a program can also deliberately throw an exception. Many exceptions that occur are deliberately thrown by Java library code or by user code when they detect a particular error condition.

To throw an exception, the throw keyword is used, followed by the exception object to be thrown. The most common case is to create the exception object on the fly, so that the code to throw an exception looks as follows:

throw new IOException(“Some required files are missing”);

We can create an instance of any public exception class from the libraries, or we can create our own exception subclass.

            Exception Classes:

The hierarchy of exception classes commence from Throwable class which is the base class for an entire family of exception classes, declared in  java.lang package as java.lang.Throwable. A throwable contains a snapshot of the execution stack at the time it was created and also a message string that gives more information about the error. This class can be instantiated and thrown by the program. The throwable class is further divided into two subclasses :-

  1. Exceptions – Exceptions are thrown if any kind of unusual condition occurs that can be caught. Sometimes it also happens that the exception could not be caught and the program may get terminated. Remember that they are a member of Exception family and can be type ofChecked or Unchecked exception.
  2. Errors – When any kind of serious problem occurs which could not be handled easily likeOutOfMemoryError then an error is thrown. Well, errors are not something which is thrown by you rather they are thrown by the Java API or by the Java virtual machine itself i.e. only the exceptions are thrown by your code and not the errors. Also Remember that they are a member of Error family.
  3. The java.lang package defines several classes and exceptions. Some of these classes are not checked while some other classes are checked.
EXCEPTIONS DESCRIPTION CHECKED UNCHECKED
ArithmeticException Arithmetic errors such as a divide by zero YES
ArrayIndexOutOfBoundsException Arrays index is not within array.length YES
ClassNotFoundException Related Class not found YES
IOException InputOuput field not found YES
IllegalArgumentException Illegal argument when calling a method YES
InterruptedException One thread has been interrupted by another thread YES
NoSuchMethodException Nonexistent method YES
NullPointerException Invalid use of null reference YES
NumberFormatException Invalid string for conversion to number YES
  1. As you have come to know that exceptions are Objects that means an object is thrown when you throw an exception. Moreover only those objects could be thrown whose classes are derived from

Throwing and catching exceptions:

For throwing and catching exceptions in java, try and catch blocks are really simple. The basic syntax follows. For this example, we’ll try to read a file that doesn’t exist. (The details of file I/O comes later in this tutorial; the important part is just that this code is risky: if the file “myfile.txt” doesn’t exist, the FileReader constructor throws a FileNotFoundException.)

System.out.println(“Ready? Go!”);

try

{

System.out.println(“I think I can…”);

FileReader reader =newFileReader(“myfile.txt”);

System.out.println(“I knew I could!”);

}

catch(FileNotFoundException ex)

{

System.out.println(“File not found.”);

}

System.out.println(“All done.”);

Whenever a method of some class could throw an exception, you should use the try/catch block. The compiler tries to run the code in the try block. If any statement in the block throws an exception, the JVM jumps to the appropriate catch block; that is, the catch block that names the thrown exception. If no code in the try block throws an exception, the catch block is skipped.

Consider the code above. If the named file exists, the try block runs to completion, and the catch block is skipped. The output is

Ready? Go!

I think I can…

I knew I could!

All done.

If the file does not exist, however, the try block halts at the FileReader constructor, and the catch block is run:

Ready? Go!

I think I can…

File not found.

All done.

Defensive Programming

Defensive programming is a form of defensive design intended to ensure the continuing function of a piece of software in spite of unforeseeable usage of said software. The idea can be viewed as reducing or eliminating the prospect of Murphy’s Law having effect. Defensive programming techniques are used especially when a piece of software could be misused mischievously or inadvertently to catastrophic effect.

Defensive programming is an approach to improve software and source code, in terms of:

  • General quality – Reducing the number of software bugs and problems.
  • Making the source code comprehensible – the source code should be readable and understandable so it is approved in a code audit.
  • Making the software behave in a predictable manner despite unexpected inputs or user actions.

Prototyping

In the progressive phase of developing a project, instead of designing and then building the completeapplication in one massive leap, prototyping can be used to examine parts of a system.A prototype is a version of the application where one part is simulated in order toexperiment with other parts. For example, one can implement a prototype to test agraphical user interface. In that case, the logic of the application may not be properlyimplemented. Instead, we would write simple implementations for those methods thatsimulate the task. For example, when calling a method to find a free seat in thecinema system, a method could always return seat 3, row 15, instead of actuallyimplementing the search. Prototyping allows us to develop an executable (but notfully functional) system quickly, so that we can investigate parts of the application inpractice.

Prototypes are also useful for single classes to aid a team development process. Often,when different team members work on different classes, not all classes take the sameamount of time to be completed. In some cases a missing class can hold upcontinuation of development and testing of other classes. In those cases it can bebeneficial to write a class prototype. The prototype has implementations of all methodstubs, but instead of containing full, final implementations, the prototype only simulates the functionality. Writing a prototype should be possible quickly, anddevelopment of client classes can then continue using the prototype until the class isimplemented.

 

Documentation

Moving towards the documentation of a project or application, afterclassifying the classes and their interfaces, and before starting to implement themethods of a class, the interface should be documented. This includes writing a classcomment and method comments for every class in the project. These should be defined in adequate detail to identify the overall purpose of each class and method.

Along with analysis and design, documentation is a further area that is often neglected by beginners. It is not easy for inexperienced programmers to see whydocumentation is so important. The reason is that inexperienced programmers usuallywork on projects that have only a handful of classes, and that are written in the spanof a few weeks or months. A programmer can get away with bad documentation whenworking on these mini-projects.

However, even experienced programmers often wonder how it is possible to write thedocumentation before the implementation. This is because they fail to appreciate that good documentation focuses on high-level issues, such as what a class or method does, rather than low-level issues, such as exactly how it does it. This is usuallysymptomatic of viewing the implementation as being more important than the design.

Interfaces as types

Interfaces as types:

When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.

As an example, here is a method for finding the largest object in a pair of objects, for any objects that are instantiated from a class that implements Relatable:

public Object findLargest(Object object1, Object object2) {

Relatable obj1 = (Relatable)object1;

Relatable obj2 = (Relatable)object2;

if ((obj1).isLargerThan(obj2) > 0)

return object1;

else

return object2;

}

By casting object1 to a Relatable type, it can invoke the isLargerThan method.

If you make a point of implementing Relatable in a wide variety of classes, the objects instantiated from any of those classes can be compared with the findLargest()method—provided that both objects are of the same class. Similarly, they can all be compared with the following methods:

public Object findSmallest(Object object1, Object object2) {

Relatable obj1 = (Relatable)object1;

Relatable obj2 = (Relatable)object2;

if ((obj1).isLargerThan(obj2) < 0)

return object1;

else

return object2;

}

 

public boolean isEqual(Object object1, Object object2) {

Relatable obj1 = (Relatable)object1;

Relatable obj2 = (Relatable)object2;

if ( (obj1).isLargerThan(obj2) == 0)

return true;

else

return false;

}

These methods work for any “relatable” objects, no matter what their class inheritance is. When they implement Relatable, they can be of both their own class (or superclass) type and a Relatable type. This gives them some of the advantages of multiple inheritance, where they can have behavior from both a superclass and an interface.

 

Interface

Interface:

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

Defining an interface is similar to creating a new class:

public interface OperateCar {

 

// constant declarations, if any

 

// method signatures

 

// An enum with values RIGHT, LEFT

int turn(Direction direction,

double radius,

double startSpeed,

double endSpeed);

int changeLanes(Direction direction,

double startSpeed,

double endSpeed);

int signalTurn(Direction direction,

boolean signalOn);

int getRadarFront(double distanceToCar,

double speedOfCar);

int getRadarRear(double distanceToCar,

double speedOfCar);

……

// more method signatures

}

Note that the method signatures have no braces and are terminated with a semicolon.

Example:
interface SessionIDCreator extends SerializableCloneable{
String TYPE = “AUTOMATIC”;
int createSessionId();
}

class SerialSessionIDCreator implements SessionIDCreator{

private int lastSessionId;
@Override
public int createSessionId() {
return lastSessionId++;
}

}

 

In above example of interface in Java, SessionIDCreator is an interface while SerialSessionIDCreator is a implementation ointerface.

 

Multiple inheritance of interfaces:

Multiple inheritance is a feature of some object oriented computer programming languages in which a class can inherit characteristics and features from more than one superclass. It is distinct to single inheritance where a class may only inherit from one particular superclass.

Simple Program On Java for the implementation of Multiple inheritance using interfaces to calculate the area of a rectangle and triangle
/* Area Of Rectangle and Triangle using Interface * /
interface Area
{
float compute(float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return(x * y);
}
}
class Triangle implements Area
{
public float compute(float x,float y)
{
return(x * y/2);
}
}
class InterfaceArea
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Triangle tri = new Triangle();
Area area;
area = rect;
System.out.println(“Area Of Rectangle = “+ area.compute(1,2));
area = tri;
System.out.println(“Area Of Triangle = “+ area.compute(10,2));
}
}
/** OUTPUT **
Area Of Rectangle = 2.0
Area Of Triangle = 10.0

/

Abstract Methods

Abstract Methods:

An abstract class can have abstract methods. You declare a method abstract by adding the abstract keyword in front of the method declaration. Here is how that looks:

public abstract class MyAbstractClass {

 

public abstract void abstractMethod();

}

An abstract method has no implementation. It just has a method signature.

If a class has an abstract method, the whole class must be declared abstract. Not all methods have to be abstract, even if the class is abstract. An abstract class can have a mixture of abstract and non-abstract classes.

Subclasses of an abstract class must implement (override) all abstract methods of its abstract superclass. The non-abstract methods of the superclass are just inherited as they are. They can also be overridden, if needed.

Here is an example subclass of MyAbstractClass:

public class MySubClass extends MyAbstractClass {

 

public void abstractMethod() {

System.out.println(“My method implementation”);

}

}

Notice how MySubClass has to implement the abstract method abstractMethod() from its superclass MyAbstractClass.

The only time a subclass of an abstract class is not forced to implement all abstract methods of its superclass, is if the subclass is also an abstract class.

Multiple inheritance is a feature of some object oriented computer programming languages in which a class can inherit characteristics and features from more than one superclass. It is distinct to single inheritance where a class may only inherit from one particular superclass.

Support we have four java class A, B, C, D

We start with simple example

1. Java Simple Inheritance Example

Class A

public class A {

 

public void a(){

System.out.println(“class A”);

}

}

Class B

public class B extends A{

 

public void a(){

System.out.println(“class B”);

}

}

Class C

public class C extends B{

 

public void a(){

System.out.println(“class C”);

}

}

Class D

public class D {

 

public static void main(String[] args) {

A a=new A();

A b=new B();

A c=new C();

 

a.a();

b.a();

c.a();

}

}

Output

class A
class B
class C

Flexibility through abstraction:

Abstraction in Java is achieved using interfaces and abstract class. abstract means something which is not complete or concrete but abstraction itself is a great programming concept and allow you to write code which is more flexible to change.

Searching elements in DOM

Most of time, to react on user-triggered event, we need to find and modify elements on the page.

The childNodeschildren and other helper links are helpful, but they allow to move between adjacent elements only.

Fortunately, there are more global ways to query DOM.

Methods

document.getElementById

A fastest way to obtain an element is to query it by id.

The following example queries the document for a div with id='info'. It doesn’t matter where is the node in the document, it will be found.

 

1 <body>
2   <div id="info">Info</div>
3   <script>
4     var div = document.getElementById('info')
5     alert( div.innerHTML )
6   </script>
7 </body>

 

Note, there can be only one element with certain id value. Of course, you can violate that and put many elements with same ids in the markup, but the behavior of getElementById in this case will be buggy and inconsistent across browsers. So it’s better to stick to standards and keep a single element with certain id.

If no element is found, null is returned.

Implicit id-valued variables

All browsers implicitly create a variable for every id.

For instance, run the following code. It will output “test”, because a is IE-generated reference to the element.

1 <div id="a">test</div>
2 <script>
3   alert(a)
4 </script>

 

 

document/node.getElementsByTagName

This method searches all elements with given tagname and returns an array-like list of them. The case doesn’t matter.

 

// get all div elements
var elements = document.getElementsByTagName('div')

 

The following example demonstrates how to obtain a list of all INPUT tags of the document and loop over results:

 

<table id=”myTable”>
<tr>
<td>Your age:</td>

<td>
<label>
<input type=”radio” name=”age” value=”young” checked/> under 18
</label>
<label>
<input type=”radio” name=”age” value=”mature”/> from 18 to 50
</label>
<label>
<input type=”radio” name=”age” value=”senior”/> older than 60
</label>
</td>
</tr>

</table>

<script>
var elements = document.getElementsByTagName(‘input’)
for(var i=0; i<elements.length; i++) {
var input = elements[i]
alert(input.value+’: ‘+input.checked)
}
</script>

It is also possible to get a first element by direct referencing:

var element = document.getElementsByTagName('input')[0]

 

There is a way to get all elements by specifying '' instead of the tag:

// get all elements in the document
document.getElementsByTagName('*')

 

Limit search by parent element

getElementsByTagName can be called on a document, but also on a DOM element.

The example below demonstrates that by calling getElementsByTagName inside another element:

<ol id=”people”>
<li>John</li>
<li>Rodger</li>
<li>Hugo</li>
</ol>
<script>

var elem = document.getElementById(‘people’)

var list = elem.getElementsByTagName(‘li’)
alert(list[0].innerHTML)

</script>

elem.getElementsByTagName(‘li’) finds all LI inside elem. The element before the dot is called *the searching context.

document.getElementsByName

For elements which support the name attribute, it is possible to query them by name.

In the example above, it was possible to use the code:

var elements = document.getElementsByName('age')

 

document/node.getElementsByClassName

This method is supported in all modern browsers excluding IE<9.

It performs a search by class name, not attribute. In particlar, it understands multiple classes.

The following example demonstrates how it finds an element using one of the classes.

Please use other browser than IE<9 to run it.

 

1 <div class="a b c">Yep</div>
2 <script>
3 alert( document.getElementsByClassName('a')[0].innerHTML )
4 </script>

 

Like getElementsByTagName, it can be called for a DOM element.

 

Practice

Consider the following html:

 

<!DOCTYPE HTML>
<html>
<body>
<label>The table</label>

<form name=”age-form”>

<table id=”age-table”>
<tr>
<td id=”age-header”>Your age:</td>
<td>
<label>
<input type=”radio” name=”age” value=”young”/> under 18
</label>
<label>
<input type=”radio” name=”age” value=”mature”/> 18 to 50
</label>
<label>
<input type=”radio” name=”age” value=”senior”/> after 60
</label>
</td>
</tr>
</table>

</form>
</body>

Here are the tasks which base on the HTML above.

Find all labels inside the table. The result should be an array (or pseudo-array) of labels.

Solution

The solution:

var table = document.getElementById('age-table')
var labels = table.getElementsByTagName('label').

Summary

There are 5 main ways of querying DOM:

  1. getElementById
  2. getElementsByTagName
  3. getElementsByName
  4. getElementsByClassName (except IE<9)

All of them can search inside any other element.

Modifying the document

DOM modifications is the key to making pages dynamic. Using the methods described below, it is possible to construct new page elements and fill them on-the-fly.

Creating elements

There are following methods for creating new elements in DOM:

document.createElement(tag)
Creates a new DOM element of type node:

var div = document.createElement('div')
document.createTextNode(text)
Creates a new DOM element of type text:

var textElem = document.createTextNode('Robin was here')

The createElement is the most commonly used method, but createTextNode is also good. It creates a text node that can be appended to another element.

For an empty element, creating a text node and appending it works much faster than innerHTML in most modern browsers.

But innerHTML is simpler and supports nested tags, so they both find their place in the world.

 

Cloning

An element can also be cloned:

elem.cloneNode(true)
Clones an element deeply, with all descendants.
elem.cloneNode(false)
Clones an element only, with attributes, but without children.

 

<!DOCTYPE html>
<html>
<body>

<ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
<ul id="myList2"><li>Water</li><li>Milk</li></ul>

<p id="demo">Click the button to copy an item from one list to another</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var itm=document.getElementById("myList2").lastChild;
var cln=itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
</script>

<p>Try changing the <em>deep</em> parameter to false, and only an empty LI element will be cloned.</p>
</body>
</html>

Adding elements

To do something with the element, you need to call the corresponding method of its parent:

parentElem.appendChild(elem)
Appends elem to the children of parentElem.The following example demonstrates creating and adding new element to BODY:

<div>…</div>
<script>
var div = document.body.children[0]

var span = document.createElement(‘span’)
span.innerHTML = ‘A new span!’
div.appendChild(span)
</script>

The new node becomes a last child of the parentElem.

 

parentElem.insertBefore(elem, nextSibling)
Inserts elem into the children of parentElem before the element nextSibling.The following example inserts a new node before the first child:

<div>

</div>
<script>
var div = document.body.children[0]

var span = document.createElement(‘span’)
span.innerHTML = ‘A new span!’
div.insertBefore(span, div.firstChild)
</script>

Note that you insertBefore with second argument null works as appendChild.

 

elem.insertBefore(newElem, null// same as
elem.appendChild(newElem)

 

All insertion methods return the inserted node.

Removing nodes

There are two main methods for removing nodes from DOM:

parentElem.removeChild(elem)
Remove the elem from the children of parentElem.
parentElem.replaceChild(elem, currentElem)
Replace the child element of parentElem, referenced by currentElem with the elem.

Both of them return a removed node which can later be reinserted into the DOM.

 

If you want to move an element, you don’t have to remove it first.

elem.appendChild/insertBefore remove elem from it’s previous place automatically.

The following example moves the last child to the top of children list:

<div>First div</div>
<div>Last div</div>
<script>
var first = document.body.children[0]
var last = document.body.children[1]

document.body.insertBefore(last, first)
</script>

The removal occurs automatically when insertion methods are called for a node which already has a parent.

 

Tasks and examples

Write a function which removes an element from DOM without referencing its parent.

The syntax should be: remove(elem)

 

<div>Very</div>
<div>Secret</div>
<div>Child</div>

<script>
var elem = document.body.children[0]

function remove(elem) { /* your code */
remove(elem) // <– should remove the element
</script>

Open solution

 

The parent of elem is referenced by the parentNode property.

And better don’t forget to return the removed element for compatibility.

So the code can be like this:

function remove(elem) {
  return elem.parentNode.removeChild(elem)
}

 

Write a function insertAfter(elem, refElem) to insert elem right after refElem.

<div>Very</div>
<div>Secret</div>

<script>
var elem = document.createElement(‘div’)
elem.innerHTML = ‘**Child**’

function insertAfter(elem, refElem) { /* your code */

insertAfter(elem, document.body.firstChild) // <— should work
insertAfter(elem, document.body.lastChild) // <— should work

</script>

Solution

To insert an element after refElem, we can insert it before refElem.nextSibling.

But what if there is no nextSibling? That means refElem is the last child of its parent, so we can just call appendChild.

The code:

function insertAfter(elem, refElem) {
var parent = refElem.parentNode
var next = refElem.nextSibling
if (next) {
return parent.insertBefore(elem, next)
} else {
return parent.appendChild(elem)
}
}

But the code could be much shorter if it used insertBefore null second argument feature:

function insertAfter(elem, refElem) {
    return elem.parentNode.insertBefore(elem, refElem.nextSibling)
}

If there is no nextSibling then the second argument of insertBefore becomes null and then insertBefore(elem,null) works as appendChild.

Write a function removeChildren to remove all children of an element.

<div>Very</div>
<div>Secret</div>
<div>Children</div>

<script>
function removeChildren(elem) { /* your code */

removeChildren(document.body) // makes BODY absolutely empty
</script>

Solution

First, let’s check a way how it shouldn’t be done

1 function removeChildren(elem) {
2   for(var k=0; k<elem.childNodes.length;k++) {
3     elem.removeChild(elem.childNodes[k])
4   }
5 }

If you check it in action – you’ll find that it doesn’t work.

That’s because childNodes always starts from 0, it autoshifts when first child is removed. But k increases +1 every iteration. So, k skips half of nodes.

The right solution:

1 function removeChildren(elem) {
2    while(elem.lastChild) {
3        elem.removeChild(elem.lastChild)
4    }
5 }

Another solution:

function removeChildren(elem) {
   elem.innerHTML = ''
}

 

 

Create an interface to generate the list.

For each item:

  1. Prompt the user for it’s contents.
  2. Create the item and append it to UL.
  3. The process ends when user presses ESC.

All elements must be created dynamically.

P.S. prompt returns null if user pressed ESC.

Solution

The solution is self-descriptive:

<!DOCTYPE HTML>

<html>
<body>
<h1>Creation of the list</h1>

<script>
var ul = document.createElement(‘ul’)
document.body.appendChild(ul)

while (true) {
var data = prompt(“Enter the contents for the item”, “”)

if (data === null) {
break
}

var li = document.createElement(‘li’)
li.appendChild(document.createTextNode(data))
ul.appendChild(li)
}
</script>

</body>
</html>

Note checking for null value as a loop-breaking condition. The prompt only returns it when ESC is pressed.

LI contents is populated by document.createTextNode to ensure proper work of <, > etc.

Summary

Creation methods:

  • document.createElement(tag) – creates a new element node.
  • document.createTextNode(value) – creates a new text node with given value
  • elem.cloneNode(deep) – clones the element

Inserting and removing methods are called from parent node. All of them return elem:

  • parent.appendChild(elem)
  • parent.insertBefore(elem, nextSibling)
  • parent.removeChild(elem)
  • parent.replaceChild(elem, currentElem)