CRUD (Create, Read, Update, Delete) is common operations in data storage, but now I will try to use DOM (Document Object Model) doing CRUD operations toward document content (and I think that is one of DOM objective). DOM can be used for doing CRUD operations easily and effectively. OK that’s enough for the buzz words let’s make the job done!
1. Create an Element
To create an element use document.createElement(<elmName>) method. This method receives one parameter that is the name of element that will be created. DOM method document.createTextNode(<text>) is similar to document.createElement but will create a text node instead of an element. The parameter received by document.createTextNode is text that will be created. The other DOM method that important in creating an element is appendChild(<elem>), this method will append the element specified as parameter to an element. Below is an example of add a <li> element to a <ul> element:
var ul = document.getElementsByTagName("ul")[0];
var li = document.createElement("li");
var text = document.createTextNode("'li' element.");
li.appendChild(text);
ul.appendChild(li);
2. Read Text of an Element
Please pay a special attention that a text in DOM is considered as a node, so we have to navigate to its text node first before we retrieve / read the node value. So, if ‘elm’ is a variable that point to a <li> element the following code:
var text = elm.firstChild.nodeValue;
will retrieve the text inside a <li> element and store the value to a variable named ‘text’.
3. Update an Element Content
Update operation really similar to read operation, except updating an element means we change the node value with the new one. If ‘elm’ point to a <li> element, the following code:
var newValue = "New text node value";
elm.firstChild.nodeValue = newValue;
will change the node value inside <li> element with the content of ‘newValue’ variable.
4. Delete an Element
Here, delete an element has two meanings. First delete the text node inside an element, second delete the element itself. Deleting an element can be accomplished using removeChild(<elm>) method. This method receives one parameter, that is child element that will be deleted.
This line of code:
elm.parentNode.removeChild(elm);
will remove ‘elm’ element.
I have write a simple code that demonstrate how to create, read, update, and delete (CRUD) the document content using DOM. I use the Javascript events and blend it with DOM to accomplished CRUD operations, so basic understanding of Javascript events will really helpful.
The code consists of two portions, first portion is html code (crud.htm):
<html>
<head>
<title>CRUD Operations: Complete</title>
<script lang=”javascript” type=”text/javascript” src=”crud.js” >
</script>
</head>
<body>
Want to know why DOM is awesome??
One of the possible answer is: with DOM we can create, read (retrieve), update, and delete document content quickly and easily.
<p/>
<b>Try the following example!</b>
<br/>
<b>
1. Press ‘Add’ button to add a new <li> element.<br>
2. Move the mouse cursor over a <li> element below.<br>
3. Click desired <li> element to read the node value.<br>
4. Hold down ‘Shift’ key and click desired <li> element to update the node value.<br>
5. Hold down ‘Ctrl’ key and click desired <li> element to delete the <li> element.<br>
</b>
<p>
<form id=”frm” name=”frm” style=”background-color:yellow; border:solid 2px; border-color:goldenrod;”>
<ul><b> And here is the list of <li> element:</b>
<li>First li element.</li>
<li>Second li element.</li>
<li>Third li element.</li>
<li>Fourth li element.</li>
<li>Fifth li element.</li>
</ul>
<p>
<input type=”button” id=”btnCreate” onclick=”addLiElement()” value=”Add New <li> Element” />
<p>
</form>
</body>
</html>
The other one is Javascript code (crud.js, this code is referred by html code), and this is the Javascript code:
window.onload = handleCRUD;
function addLiElement()
{
// ask input text for new <li> element
var txt = window.prompt("Text: ");
var text = document.createTextNode(txt);
// create <li> element
var elm = document.createElement("li");
/* retrieve the first <ul> element (and the only one). */
var ul = document.getElementsByTagName("ul")[0]; elm.appendChild(text);
ul.appendChild(elm);
handleCRUD();
}
function handleCRUD()
{
var lis = document.getElementsByTagName("li");
for (var i=0;i<lis.length;i++) {
lis[i].onmouseover = function()
{
this.style.backgroundColor = "gainsboro";
};
lis[i].onmouseout = function()
{
this.style.backgroundColor = "yellow";
};
/* ‘click’ event handles read, update, or delete operation */
lis[i].onclick = function(e)
{
// IE handles event through window.event property
e = e||window.event;
/* again IE handles target (source) element as srcElement */
var elm = e.target||e.srcElement;
if (e.ctrlKey) {
/* because 'ctrl' key is pressed, it will be delete operation */
var txtNode = elm.firstChild;
// first, delete the text node
txtNode.parentNode.removeChild(txtNode);
// second, delete the <li> element
elm.parentNode.removeChild(elm);
return;
}
if (e.shiftKey) {
/* because 'shift' key is pressed, it will be update operation */
var newValue = window.prompt("Enter new value: ");
elm.firstChild.nodeValue = newValue;
return;
}
else {
/* neither 'ctrl' nor 'shift' key is pressed, it will be read
operation */
/* now, here we retrieve the content (text) of an element */
var content = elm.firstChild.nodeValue;
window.alert(content);
return;
}
};
}
};
The javascript code started with window.onload that executed after the document is loaded, and passed handleCRUD() function to it. Inside handleCRUD we install mouseover, mouseout, and click events foreach <li> element exist in document.
What is done by each event can be explained as follow:
‘Add’ button onclick: adds an li element to the document.
onmouseover: changes the background color of a <li> element to ‘gainsboro’ when mouse cursor enters it.
onmouseout: restores the background color of a <li> element to ‘yellow’ when mouse cursor leaves it.
onclick, this event has three meanings:
- when we click an <li> element along with ‘Ctrl’ key pressed, then the specified <li> element will be deleted.
- when we click an <li> element along with ‘Shift’ key pressed, then the node value of specified <li> element will be updated.
- when we click an <li> element and neither ‘Ctrl’ key nor ‘Shift’ key is pressed then we simply read the specified <li> element.
onclick event handler receive one parameter that is event object (‘e’ in this code), but event object in Internet Explorer (IE) available through window.event property. So we need a regular checking ‘e’ will be still ‘e’ or if the browser is IE e will be filled with window.event.
e = e||window.event;
The target (non IE browser) / srcElement (IE) are properties of event object contains a reference to the element that fired to the event. We get target / source element with the following code:
var elm = e.target||e.srcElement;
This is screenshot output produced by crud.htm & crud.js:
To make the same output as screenshot above puts crud.htm & crud.js in the same directory, type the location in address bar of your browser and you should see the same result.
Thanks for your attentions, see you next time…