知识点19:Dom(Document Object Model)

You might find handy when you're starting to work on manipulating web pages and changing the content of your web page on the fly. And that's the notion of the Document Object Model.

Now, the document object is a very special object in JavaScript that organizes your entire web page under this sort of umbrella of an object.

And so inside of the document object are objects presenting the head and body of your web page.

Inside of those are other objects, et cetera, et cetera, until your entire web page has been organized in this big object.

So if we have an object that refers to our entire web page, that means by calling the correct methods to manipulate that object or modifying certain of its properties, we can change the elements of our page programmatically using JavaScript instead of having to code things with, say, HTML.


So here's an example of a very simple web page, right?

It's got HTML tags, a head.

Well, what might the document object for this look like?

Well, it's a little scary maybe at first. But it's really just a big tree. And at the very root of it is document.

Inside of the document is another object referring to the HTML of my page.

And so this entire hierarchy can be represented as a big tree with lots of smaller little things coming out of it.


Now, of course, when we're programming, we don't think of things like a big tree. We want to see actual code related things.

And fortunately, we can use our developer tools to actually take a look at this website's document object. And let's do that. So I've opened up a browser tab.

And I've opened up Developer Tools. And in my video on JavaScript, I mentioned that the console is not only someplace where we print information, it's also a place where we can input information. In this context, what I'm going to say is I would like to get back the document objects, so I can start to have a look at it.

So how might I do this?

Well, if I want to organize it really nicely,

I'm going to say console.dir, D-I-R. Now, I use console.log to just print out something very simple. But if I want to organize this hierarchically like an object, I want it sort of structured like a directory structure.

So I want to console.dir document. I'm going to hit Enter. And right below it now, and I'll zoom in here,

I've got this response document with a little arrow next to it. Now, when I open this arrow, there's going to be a lot of stuff.

But we're going to ignore a lot of it and just kind of focus on the most important part, so we can begin to navigate this document. There's a lot more to the DOM than just parent nodes and child nodes.

There's a lot of ancillary stuff.

So I'm going to open this up.

And there's a whole lot of stuff that pops up. But all I care about is right here, child nodes. Let's open that up.

Inside of there I see something familiar, HTML. So inside of our document one level down, HTML. I open that up. What are we expecting?

If you recall from our diagram, what should we find inside of HTML?
What two nodes are below it in the tree? Let's find out. We open up HTML.

We go down to its child nodes. Pop that open.

There's head and body. And we can open up the head.

Go to its child nodes. Well, there's the title.

And we could go on and on like this forever. We could do this with body as well.

But there is a way for us to look at the document organized as a big object. And if we look at is a big object that looks a lot like code, that means that we can start to manipulate this big object using code to change what our website looks and feels like.

So that's a pretty powerful tool we have at our disposal now.

So as we just saw, the document object itself and all of the objects inside of it have properties and methods, just like any other object that we've been working with in JavaScript.

But we can use those properties and use those methods to sort of drill down from the big document and get lower and lower and lower, finer and finer grains of detail, until we get to a very specific piece of our web page that we want to change.

And when we update properties of the Document Object or call those methods, things might happen on our web page. And we don't need to do any refreshing to have those changes take effect.

(即实时更新)


And that's a pretty cool ability to have when we're working with code.

So what are some of these properties that are part of a document object? Well, you probably saw a couple of them really quickly as we were zipping through the giant document object we just saw in the web browser.

But a couple of these properties might be things like inner HTML. And you might even recall me using this in the JavaScript video at the very end when I was talking about events.

What was this inner HTML? Well, it's just what's in between the tags. And so the inner HTML, for example, of the title tag, if we had kept going in that example a moment ago, would have been hello world. That was the title of our page.

Other properties include node name, which is the name of an HTML element such as title.

ID, which is the ID attribute of an HTML element. Recall that we can specially indicate specific elements of our HTML with an ID attribute, which usually comes in handy in the context of CSS, specifically.

Parent node, which is a reference to what's just up above me in the DOM.

And child nodes, which is a reference to what's down below me. And we saw a lot of that just looking through. Child nodes, that's how we got lower and lower into the tree.

Attributes, that's just an array of attributes of the HTML element. So an example of attributes might be if you have an image tag, it usually has a source attribute, maybe a height and a width attribute. And so that would just be an array of all of the attributes associated with that HTML element.

Style is another one that does represent the CSS styling of a particular element. And later on in this video, we'll specifically leverage style to make a couple of changes to our website.

So those are some properties.


And there are also some methods that we can use to also more quickly maybe isolate elements of the Document Object.

Perhaps, the most versatile of these being getElementById. So I might say something like, because remember it's a method of the Document Object, document.getElementById. And inside of those parentheses, specify an HTML element with a particular ID attribute that I've previously set, and I'll immediately go right to that element of the overall website. So I don't have to maybe drill down through every single layer. I can just use this method to find it, sort of like a heat seeking missile, right? It just goes and finds exactly what it's looking for.

GetElementsByTagName is very similar in spirit. Maybe this would find all of the bold tags or all of the p tags and give me an array of everything that I could then work with.

appendChild adds something one level down in the tree. So I can add an entire new element one level lower.

Or I can remove an element that's one level lower as well if I want to delete something from my web page.

Now, a quick coding note and a quick headache saving note, hopefully.

Watch out!

getElementById-- the d is lowercase.

I can't tell you how many times I have used getElementById and capitalized the d there.

Because it's really common. If we write the word ID, it's usually capital I capital D. And my code just doesn't work. And I can't figure out why.

This is a really, really, really common bug that everybody makes, even experts that have been doing this forever. So just be aware, getElementById, that d is lowercase. And hopefully, that saves you several minutes at least of heartache.


So what does all of this tell us:

This can get wordy, this document.getElementByID, maybe have a long tag name, maybe you do more calls later on.

Things can get a little bit wordy. And as programmers, as you've probably seen in many of these videos, we don't like wordy things.

We like to be able to do things quickly. So we would like a more concise way to say something. So this sort of leads to the notion of something called jQuery.

Now jQuery is not JavaScript. It's not part of JavaScript. It is a library that was written by some JavaScript programmers about 10 years ago.

And its goal is to simplify this what's called client side scripting, which is basically what we were just talking about with DOM manipulations.

And so if I wanted to modify the background color of my web page, maybe a specific Div.

Here, I'm apparently getting ElementById colorDiv.

And I want to set its background color. If I'm just using pure JavaScript using the Document Object Model, that's a lot of stuff, right?

document.getElementByID colorDiv.style.backgroundColor=green.

That was a lot to say. It's a lot to type, too. And so in jQuery, we can maybe say this a little bit more concisely.

The trade off being it's maybe a little bit more cryptic all of a sudden.

At least the long is a bit more explanatory as to what we're doing. This dollar sign, parentheses, single quote, hash, colorDiv, right?What does that mean? Well, that's basically just document.getElementByID colorDiv.

But it's this sort of shorthand way of doing it using jQuery.

Let's just take a look now at a couple of different ways that I might actually use this Document Object Model to manipulate pieces of my site.

In particular, we're going to be working on manipulating the color of a particular Div, colorDiv, on a web page. So let's take a look at that.

And then at the very bottom here, I apparently try and do this using jQuery as well. And in this case, I'm not actually calling a function at all. I've just said the class that I'm using for this button is a jQ button. That's it.

So how does jQuery know what I'm doing? Well, this is one of the advantages slash disadvantages of jQuery. It can allow me to do things very concisely, but maybe not as intuitively.

Here, though, what's going on?

Apparently, creating an anonymous function that loads whenever my document is ready, so document.ready, some function is going to happen.

Basically, when is a document ready? It's when my page has loaded.

So as soon as my page has loaded, the following function is always ready. It says, if an object of type jQButton, or if class jQButton has been clicked, execute this function.

So here's two anonymous functions, one defined inside of the other.

So my entire context here so far is my page when it loads it calls this function. And this function is waiting for a button to be clicked. And when a button is clicked, jQ button specifically is clicked, it calls this other function, which is going to set the background color of colorDiv to be whatever text is in between the tags.

This is the notion of which button was clicked. But otherwise, this is sort of behaving similar to an event. It's just the same way I would express this in jQuery.

Again, it's probably a lot more intimidating. It's not as clear as something like event.js, which is maybe a little bit more verbose, but a little bit less intimidating.

But if we pop back over to my browser window, if I start clicking--well, that changed to purple.

This is green using the string method. This is orange using the event handler. This is red using jQuery, right? They all behave exactly the same. They just do it using different approaches to solve the problem.

JQuery网站

附:

其他三个方法,从wordy到相对简练的顺序

1 individual functions for background color:

we'll take a look at what those five functions are:

2 One single function for background color

a more general case JavaScript function:

3 Event handler for background color

The End

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,222评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,455评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,720评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,568评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,696评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,879评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,028评论 3 409
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,773评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,220评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,550评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,697评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,360评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,002评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,782评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,010评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,433评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,587评论 2 350

推荐阅读更多精彩内容