Contenido del Curso
HTML & JavaScript Interactivity for Beginners
HTML & JavaScript Interactivity for Beginners
DOM Intro and HTML DOM Document Object
What is DOM?
As you already know, a web page is a collection of HTML elements. So when it loads in a web browser, it creates a graphical representation of all the HTML elements in the form of a tree called the DOM(Document Object Model). Each HTML element in the tree represents an object.
Let's take a look at the DOM with a coding example.
index
index
index
The browser represents the above code in the following form:
Now you know what DOM is. Next is the time to dive into the uses of DOM.
What are the uses of DOM?
HTML elements are static, which implies that you can't make any changes to them live. However, websites these days are seldom static and instead are dynamic.
Let's say, for instance, you want to hide a particular paragraph with a click of a button and change the color of all the anchor links on the page load. Both these instances are possible by manipulating the DOM with JavaScript.
For now, let's look at what you can do with DOM by using JavaScript:
- Change the attributes and styles of an HTML page;
- Add new HTML elements by responding to events for an HTML element;
- Delete HTML elements by responding to events for an HTML element;
- Add new styles and attributes to an HTML element.
Next, you'll discover how all these manipulations are possible with JavaScript.
How can you access the DOM with JavaScript?
Think of all the HTML elements that you saw above as objects.
Then think of the root of these objects as the document
object, which houses all the objects, the web page.
So to access any DOM element using JavaScript, you need to do so via the document
object methods, which you'll find out next.
Methods
Here are the primary methods for now:
getElementByID(id)
=> gets the HTML element by its id attribute. Here the ID is passed as a parameter;getElementsByTagName(tag_name)
=> gets the HTML elements by tag name as specified in the parameter;getElementsByClassName(class_name)
=> gets the HTML elements by class name as specified in the parameter.
Now let's work with code for a change, shall we? Consider the following code, which has no contents in its <h1>
tag.
Now then let's write its content using JavaScript:
index
index
index
This change was possible with the help of the innerHTML
property.
Properties
You can add properties to methods, as you saw above, to change the contents of HTML elements. In the next chapter, you'll learn more about the properties.
¡Gracias por tus comentarios!