JavaScript for DOM applications

Source: Internet
Author: User

The so-called application for DOM. And I'm just going to teach you how to interact with the DOM elements in the JavaScript operation page. I believe it's possible that most people come here to learn JavaScript, mostly by using the DOM elements in the page to do some really useful interaction. So I'm just here to teach you the most practical, most useful JavaScript app. But the premise is that you should have some JavaScript or jquery programming basics. I don't have much to say.
Today's first article teaches you how to use JavaScript to get DOM elements in a page. This is important. I'll do it against jquery.
If the element in the page is an id attribute
<div id= "Dom" ></div>

Method of JQ: $ ("#dom"),
Native JS method: var a = document.getElementById ("Dom"), this a is equivalent to $ ("#dom");

If I want to get an element under the parent element
<div id= "Dom" >
< span></span>
</div>

Method of JQ: $ ("#dom span"),
Native JS method: var b = document.getElementById ("Dom"). getElementsByTagName ("span") [0]; this b is equivalent to $ ("#dom span")
In fact, there is a simple way of var B = document.getElementById ("Dom"). Childnodes[0] But there's going to be a problem at FF, and we'll talk about it later.

Get a set of elements in a page
<div id = "Dom" >
< ul>
< li></li>
< li></li>
< li></li>
< ul>
</div>

Method of JQ: $ ("#dom ul Li") or $ ("#dom Li") or $ ("#dom > Li"),
Native JS method: var c = document.getElementById ("Dom"). getElementsByTagName ("Li"), but this c is not the same as above, because it cannot be used directly as above JQ. You need a For loop in order to use it together. If a single use for example I only use the first Li, I only need var c = document.getElementById ("Dom"). getElementsByTagName ("li") [0], with the second one is var C = document.getElementById ("Dom"). getElementsByTagName ("Li") [1], and so on. Because DOM elements are stored as arrays in JS.

The above are all well understood. Now what I'm going to talk about is what everyone is used to. But one of the most troublesome properties to get in native JS is the class attribute,
< div class = "dom" >
</div>

Method of JQ: Very simple $ (". Dom");
Native JS method: This is a bit of a hassle, you need to write a function. Because native JS does not provide a way to get class directly. So we need this. I'll write the function first.
function $class (domclass) {
var odiv = document.body.getElementByTagName ("*");
var A;
for (var i = 0;i<odiv.length;i++) {
if (Odiv.classname ==domclass) {
A = Odiv
}
return A;
}
}
It is simple to use this function to obtain only the var d = $class ("Dom");

Let me just say the meaning of this function,
var odiv = document.body.getElementByTagName ("*");
This means getting all the DOM elements in the page

for (var i = 0;i<odiv.length;i++) {
if (Odiv.classname ==domclass) {
A = Odiv
}
This is to traverse all the elements of the page and then compare them to their class. If it's the same parameter as the Domclass we passed in, take this element to A;
return A;

So use var d = $class ("Dom"), which is equivalent to var d = A;

We all know that in JQ it is very convenient to get a sibling element of an element, a parent element, a child element, and so on. In fact, in the original JS also have these attributes. is almost the same as JQ but less than JQ. But it is a bit more troublesome to use than JQ. Mainly because of the FF browser, because FF will also treat your newline as a DOM element. For example
<div id = "Dom" >
< div></div>
< div></div>
</div>
I used the native JS to get the child element under the element with ID DOM. In my first chapter, the method is var a = document.getElementById ("Dom"). getElementsByTagName ("div"); Can alert (a.length) prompt will be 2, but we now take another approach to get is the var B = document.getElementById ("Dom") I mentioned in the previous chapter. ChildNodes; If such alert (b.length) IE is not a problem or 2, but in the FF browser will be prompted is 4, this is because the FF is a newline also as an element.
So we have to deal with the properties of JS. The simplest way to deal with ideas is to iterate over these elements. The element type is a space and the text is deleted. The handler function is like this
function Del_space (elem) {
var elem_child = elem.childnodes;
for (Var i=0;i<elem_child.length;i++) {
if (Elem_child.nodename = = "#text" &&!/\s/.test (Elem_child.nodevalue))
{Elem.removechild (Elem_child)}
}}

Let me explain this function.
var elem_child = elem.childnodes;
Throw the elem elements of the passed in into the elem_child;

for (Var i=0;i<elem_child.length;i++) {
if (Elem_child.nodename = = "#text" &&!/\s/.test (Elem_child.nodevalue))
{Elem.removechild (Elem_child)}
}
Traverse these child elements. If these elements have a node type that is text and the node value of the text type node is empty. Just remove it.

(NodeName is a property of JS, get the node type of this node,/\s/the normal expression of the non-null character in JS. Preceded by an exclamation point indicates a null character. Test is a method of JS, that is, the inside of it and things outside the comparison. NodeValue means to get the value in this node removechild is also a way to delete a child element of the outside element)

This only needs to call the function before invoking these properties to clean up the space can be used for example
<div id = "Dom" >
<div></div>
<div></div>
</div>

<script>
function dom () {
var a = document.getElementById ("Dom");
Del_space (a); Calling a function that cleans up spaces
var B = a.childnodes; gets all the child nodes of A;
var c = A.parentnode; Gets the parent node of A;
var d = a.nextsbiling; get the next sibling node of a
var e = a.previoussbiling; Get the previous sibling node of a
var f = a.firstchild; Gets the first child node of a
var g = A.lastchild; Gets the last child node of a

}
</script>

(In addition.) var B = a.childnodes; Gets an array, so for example I want to use the first node is childnodes[0]; I want to use the second node is childnodes[1]; and so on)

The first two chapters are about getting DOM elements. This chapter begins with how to manipulate the DOM. 1. Manipulating the DOM element on the page is nothing more than manipulating the style of the DOM element. If the DOM element doesn't have a style, it's not working. 2. We can also directly use JS to dynamically write DOM elements to HTML.
We'll talk about these two applications in this chapter today.
(a) manipulate the existing DOM elements in the HTML.
As I said above, the operation of the existing DOM element is nothing more than the manipulation of the style. So we're going to get the style of this DOM element first. Before you talk about getting the style of a DOM element. Let's start by referring to the way the DOM element styles are linked. There are three kinds.

One is to write the style directly in the HTML document, for example
<div style= "width:300px;height:200px;background000;" ></div>.

The second is to insert an HTML document header with a style tag such as
<style>
#dom {width:300px;height:200px;background000;}
</style>

The third is the way we used to link in such as
<link rel= "stylesheet" type= "Text/css" href= "Css.css"/>

These three kinds of using JS to manipulate its style is not the same way
Emphasis we say the first kind of chain into the style operation, because it is the most common, but also the most convenient.
The second kind of chaining into style operation is troublesome.
The third kind of chain into the style operation trouble not to say, and can not directly modify the style, want to modify the words must also use the first method, that is to see can not touch

The first way to link into a style
Example <div id= "Dom" style= "width:300px;height:200px;background000;margin-top:10px;" ></div>
Getting its height attribute, first of all, is to get DOM elements, using the methods of the previous chapters
var a = document.getElementById ("Dom");
Again to get its height attribute, it's simple
var h = a.style.height;
And so on, get the width, get the background color
var w = a.style.width;
var bg = a.style.background;
Note that the margin attribute is margin-top;
To get this can't be written directly
var mt = A.style.margin-top;
To use the camel's notation mentioned in JQ.
var mt = A.style.margintop;

It is of course useless to get it, we need to be able to modify it, and it is convenient to modify it. For example, we want to change the height of it to 100, very simple, just one sentence
A.style.height = "100px";
Other and so on, I don't say much;


The second way to chain into a style
<style>
#dom {width:300px;height:200px;background: #000; margin-top:10px;}
</style>
This operation requires a separate browser. Because IE and FF are different for this acquired code, such as the way to get the height is
var domcss = document.stylesheets[0].cssrules| | Document.stylesheets[0].rules;
var a = Domcss[0].style.height;
The change is like this.
Domcss[0].style.height = "100px";
I don't want to explain why it's written like this. Everyone is interested in checking it out for themselves;

The third way to chain into styles
<link rel= "stylesheet" type= "Text/css" href= "Css.css"/>
This operation also needs to differentiate between browsers.
Getting the words is usually a function, the function is like this
function Currentstyle (Element) {
return Element.currentstyle | | Document.defaultView.getComputedStyle (element, NULL);
}
If we have the height attribute in the Css.css file,
The Get method is var a = Currentstyle ("Dom"). Height;
Can not be directly modified by the method here, only the first method of modifying
I don't want to explain why it's written like this. Everyone is interested in checking it out for themselves;

(b) Dynamically create DOM elements with JS.
In fact, this is very simple is a few JS method, but to build a house like a step-by-step, such as I want to create a DOM element such as:
<div id= "Dom" style= "Width:100px;height:100px;background: #000; margin-top:10px;" ></div>

The first step is to create a div node. var newobj = document.createelement ("div");

The second step is to add an id attribute to this section, and the property name is Dom. Newobj.setattribute ("id", "dom");

The third step, to add attributes to this node there are two kinds of side, one is what we said before the modified style is such newobj.style.width = "100px"; there is a second step to use the method Newobj.setattribute ("width" , "100px"), other properties, etc.

The fourth step is to put this node into the HTML document, the method is such document.body.appendChild (newobj) This sentence means this. Document.body is getting the BODY element.
, AppendChild (newobj) is to add a child element to the BODY element that is the node we created.


If you want to remove this node is so Document.body.removeChild (newobj);
(This can be replaced by the element you want to add a child element to, such as I want to add a node to this element with ID con, and we'll write document.getElementById ("con"). AppendChild (newobj))


From this beginning, we will tell you some practical effect of the wording. Of course the first is our cute tab tab, which is handy for writing tabs with JQ and a lot of methods. In fact, with native JS Write Tab method is also a lot. I'm going to write a few for you to see.
One, click on the method of parameter transfer
<script>
Function tab (DOM) {
var list = document.getElementById ("list"). getElementsByTagName ("Li");
var con = document.getElementById ("con"). getElementsByTagName ("div");
for (Var i=0;i<list.length;i++) {
if (list==dom) {
List.classname = "on";
Con.style.display = "block";
}
else{
List.classname= "";
Con.style.display= "None";
}
}
}
</script>
< div id= "list" >
< ul>
< li class= "on" >1</li>
< li>2</li>
< li>3</li>
< li>4</li>
</ul>
</div>
< div id= "con" >
< div style= "display:block;" >111111</div>
< div style= "display:none;" >222222</div>
< div style= "display:none;" >333333</div>
< div style= "display:none;" >444444</div>
</div>
Let me explain.
var list = document.getElementById ("list"). getElementsByTagName ("Li");
var con = document.getElementById ("con"). getElementsByTagName ("div");
Get the DOM element, that's needless to say. The first thing you do is get the element.
for (Var i=0;i<list.length;i++) {
if (list==dom) {
List.classname = "on";
Con.style.display = "block";
}
else{
List.classname= "";
Con.style.display= "None";
}
Walk through all the LI elements, find and pass in the DOM of the same thing, then set his class to on, and the corresponding Div to show, the other all the classname set to empty, and the corresponding div to hide.
That's probably it. But everyone must have found the shortcoming of this writing, that is, each Li should set an onclick time to pass to its own. This is a bit of a violation of the structure and performance of the principle of separation. So we're going to change the wording.
Second, direct write mouse event method
<script>
Function tab () {
var list = document.getElementById ("list"). getElementsByTagName ("Li");
var con = document.getElementById ("con"). getElementsByTagName ("div");
for (var i = 0;i<list.length;i++)
{
List.onclick=function () {
for (Var i=0;i<list.length;i++) {
if (list==this) {
List.classname = "on";
Con.style.display = "block";
}
else{
List.classname= "";
Con.style.display= "None";
}
}
}
}
}
Window.onload=function () {tab ();}
</script>
< div id= "list" >
< ul>
< li class= "on" >1</li>
< li>2</li>
< li>3</li>
< li>4</li>
</ul>
</div>
< div id= "con" >
< div style= "display:block;" >111111</div>
< div style= "display:none;" >222222</div>
< div style= "display:none;" >333333</div>
< div style= "display:none;" >444444</div>
</div>
Just a simple change can be, because there are these methods in JS can be used such as onclick,onmouseover and so on, but the use of the time I have to use all the elements of this event is traversed, if that is clicked will pass a This, We just need to decide as the first method that the list is the same as this one, and then the following action is the same as the method
(Both of these methods are relatively simple notation, in JS there are some more advanced complex wording, but the use of the idea and the two are mostly the same way of writing.) )

JavaScript for DOM applications

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.