官术网_书友最值得收藏!

DOM

The DOM is what is used to describe the structure of an HTML or XML page. It creates a tree-like structure that provides us with the ability to do everything from creating, reading, updating, and deleting nodes to traversing the tree and many more features, all within JavaScript. Let's consider the following HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
<title>DOM Example</title>
</head>
<body>
<div>
<p>I love JavaScript!</p>
<p>Here's a list of my favourite frameworks:</p>
<ul>
<li>Vue.js</li>
<li>Angular</li>
<li>React</li>
</ul>
</div>

<script src="app.js"></script>
</body>
</html>

We're able to look at the HTML and see that we have one div, two p, one ul, and li tags. The browser parses this HTML and produces the DOM Tree, which at a high level looks similar to this:

We can then interact with the DOM to get access to these elements by TagName using document.getElementsByTagName(), returning a HTML collection. If we wanted to map over these collection objects, we could create an array of these elements using Array.from. The following is an example:

const paragraphs = Array.from(document.getElementsByTagName('p'));
const listItems = Array.from(document.getElementsByTagName('li'));

paragraphs.map(p => console.log(p.innerHTML));
listItems.map(li => console.log(li.innerHTML));

This should then log the innerHTML of each item to the console inside of our array(s), thus showing how we can access items inside of the DOM:

主站蜘蛛池模板: 唐河县| 南投县| 平度市| 体育| 尚志市| 咸宁市| 盐边县| 同心县| 固安县| 无为县| 宁蒗| 霍州市| 乌拉特中旗| 仙桃市| 贵阳市| 巴马| 阿克| 安乡县| 绵竹市| 开化县| 镇雄县| 亚东县| 汝阳县| 土默特左旗| 乌拉特前旗| 荣成市| 策勒县| 大连市| 达拉特旗| 儋州市| 江都市| 富阳市| 垣曲县| 哈尔滨市| 华阴市| 于田县| 柳河县| 龙陵县| 邹平县| 明光市| 汶川县|