在本教程之前的教程中series, “如何更改 DOM”,我们介绍了如何使用内置方法从文档对象模型 (DOM) 中创建、插入、替换和删除元素。通过提高操作 DOM 的熟练程度,您可以更好地利用 JavaScript 的交互功能并修改 Web 元素。
在本教程中,您将学习如何通过修改 HTML 元素节点的样式、类和其他属性来进一步更改 DOM。这将使您更好地了解如何操作 DOM 中的基本元素。
直到最近,一个流行的 JavaScript 库称为jQuery最常用于选择和修改 DOM 中的元素。 jQuery 简化了选择一个或多个元素并同时对所有元素应用更改的过程。在 ”如何访问 DOM 中的元素,”我们回顾了在普通 JavaScript 中抓取和使用节点的 DOM 方法。
回顾,document.querySelector()
and document.getElementById()
是用于访问单个元素的方法。用一个div
与id
在下面的示例中,我们可以通过任何一种方式访问该元素。这querySelector()
方法更加健壮,因为它可以通过任何类型的选择器选择页面上的元素。
给定 HTML:
<div id="demo-id">Demo ID</div>
我们可以使用以下方式访问该元素querySelector()
方法如下:
// Both methods will return a single element
const demoId = document.querySelector('#demo-id');
访问单个元素,我们可以轻松更新元素的一部分,例如内部的文本。
// Change the text of one element
demoId.textContent = 'Demo ID text updated.';
但是,当通过公共选择器访问多个元素(例如特定类)时,您必须循环遍历列表中的所有元素。下面的代码中有两个div
具有共同类值的元素。
<div class="demo-class">Demo Class 1</div>
<div class="demo-class">Demo Class 2</div>
您可以使用querySelectorAll()
抓取所有元素demo-class
应用于他们,并且forEach()
循环遍历它们并应用更改。也可以通过以下方式访问特定元素querySelectorAll()
与处理数组的方式相同——使用方括号表示法。
// Get a NodeList of all .demo elements
const demoClasses = document.querySelectorAll('.demo-class');
// Change the text of multiple elements with a loop
demoClasses.forEach(element => {
element.textContent = 'All demo classes updated.';
});
// Access the first element in the NodeList
demoClasses[0];
Note:方法getElementsByClassName()
and getElementsByTagName()
将返回无法访问的 HTML 集合forEach()
方法querySelectorAll()
有。在这些情况下,您将需要使用标准for loop迭代集合。
这是从 jQuery 发展到普通 JavaScript 时需要注意的最重要的区别之一。重要的是要注意将这些方法和属性应用于多个元素的过程。
本教程涵盖了用于修改的属性和方法属性的元素。这些属性和方法通常会附加到事件监听器以便响应点击、悬停或其他触发器。
属性是包含有关 HTML 元素的附加信息的值。他们通常进来名称/值成对,并且可能是必需的,具体取决于元素。
一些最常见的 HTML 属性是src
的属性img
标签,该href
of an a
标签,以及class
, id
, and style
属性。有关 HTML 属性的完整列表,请查看属性列表在 Mozilla 开发者网络上。不属于 HTML 标准的自定义元素将添加前缀data-
or aria-
.
在 JavaScript 中,我们有四种修改元素属性的方法:
Method |
Description |
Example |
hasAttribute() |
Returns a true or false boolean |
element.hasAttribute('href'); |
getAttribute() |
Returns the value of a specified attribute or null
|
element.getAttribute('href'); |
setAttribute() |
Adds or updates value of a specified attribute |
element.setAttribute('href', 'index.html'); |
removeAttribute() |
Removes an attribute from an element |
element.removeAttribute('href'); |
让我们创建一个新的 HTML 文件img
具有一个属性的标签。我们将链接到通过 URL 提供的公共图像,但如果您离线工作,则可以将其替换为备用本地图像。
属性.html
<!DOCTYPE html>
<html lang="en">
<body>
<img src="https://js-tutorials.nyc3.digitaloceanspaces.com/shark.png">
</body>
</html>
当您将上述 HTML 文件加载到现代 Web 浏览器并打开内置开发者控制台,您应该看到类似这样的内容:
现在,您可以即时测试所有属性方法。
// Assign image element
const img = document.querySelector('img');
img.hasAttribute('src'); // returns true
img.getAttribute('src'); // returns "...shark.png"
img.removeAttribute('src'); // remove the src attribute and value
此时,您将已经删除了src
关联的属性和值img
,但您可以重置该属性并将该值分配给备用图像img.setAttribute()
:
img.setAttribute('src', 'https://js-tutorials.nyc3.digitaloceanspaces.com/octopus.png');
最后,我们可以直接修改属性,通过为属性分配新值作为元素的属性,设置src
回到shark.png
file
img.src = 'https://js-tutorials.nyc3.digitaloceanspaces.com/shark.png';
任何属性都可以通过这种方式以及上述方法进行编辑。
The hasAttribute()
and getAttribute()
方法通常与条件语句,以及setAttribute()
and removeAttribute()
方法用于直接修改 DOM。
The class属性对应于CSS 类选择器。这不要与ES6 类,一种特殊类型的 JavaScript 函数。
CSS 类用于将样式应用于多个元素,这与每个页面只能存在一次的 ID 不同。在 JavaScript 中,我们有className and classList属性与类属性一起使用。
Method/Property |
Description |
Example |
className |
Gets or sets class value |
element.className; |
classList.add() |
Adds one or more class values |
element.classList.add('active'); |
classList.toggle() |
Toggles a class on or off |
element.classList.toggle('active'); |
classList.contains() |
Checks if class value exists |
element.classList.contains('active'); |
classList.replace() |
Replace an existing class value with a new class value |
element.classList.replace('old', 'new'); |
classList.remove() |
Remove a class value |
element.classList.remove('active'); |
创建另一个 HTML 文件以使用包含两个元素和几个类的类方法。此外,还包括一个内联 CSS 样式表来提供一些样式来帮助我们查看工作结果。
类.html
<!DOCTYPE html>
<html lang="en">
<style>
body {
max-width: 600px;
margin: 0 auto;
font-family: sans-serif;
}
.active {
border: 2px solid blue;
}
.warning {
border: 2px solid red;
}
.hidden {
display: none;
}
div {
border: 2px dashed lightgray;
padding: 15px;
margin: 5px;
}
</style>
<body>
<div>Div 1</div>
<div class="active">Div 2</div>
</body>
</html>
当您打开classes.html
将文件导入到 Web 浏览器中,您应该会收到类似于以下内容的渲染:
The className
引入属性是为了防止与class
JavaScript 和其他可以访问 DOM 的语言中存在的关键字。您可以使用className
直接给类赋值。
// Select the first div
const div = document.querySelector('div');
// Assign the warning class to the first div
div.className = 'warning';
通过分配warning
CSS 值中定义的类classes.html
到第一个div
,您将收到以下输出:
Note:如果元素上已经存在任何类,这将覆盖它们。您可以使用以下命令添加多个空格分隔的类className
属性,或者在不使用赋值运算符的情况下使用它来获取元素上类的当前值。
修改类的另一种方法是通过classList属性,它附带了一些有用的方法。这些方法与 jQuery 类似addClass
, removeClass
, and toggleClass
方法。
// Select the second div by class name
const activeDiv = document.querySelector('.active');
activeDiv.classList.add('hidden'); // Add the hidden class
activeDiv.classList.remove('hidden'); // Remove the hidden class
activeDiv.classList.toggle('hidden'); // Switch between hidden true and false
activeDiv.classList.replace('active', 'warning'); // Replace active class with warning class
执行上述方法后,您的网页将如下所示:
因为activeDiv
元素仍然有类hidden
应用到它,它不会显示在页面上。
与在className
例如,使用classList.add()
会将新类添加到现有类列表中。您还可以添加多个类作为逗号分隔的字符串。也可以使用setAttribute
修改元素的类。
The style属性表示 HTML 元素上的内联样式。通常,样式将通过样式表应用于元素,就像本文前面所做的那样,但有时您必须直接添加或编辑内联样式。
创建一个新文件来演示使用 JavaScript 的编辑样式。使用下面包含的内容div
应用了一些内联样式来显示正方形。
样式.html
<!DOCTYPE html>
<html lang="en">
<body>
<div style="height: 100px;
width: 100px;
border: 2px solid black;">Div</div>
</body>
</html>
当在网络浏览器中打开时,styles.html
看起来像这样:
编辑样式的一种选项是setAttribute()
.
// Select div
const div = document.querySelector('div');
// Apply style to div
div.setAttribute('style', 'text-align: center');
但是,这将从元素中删除所有现有的内联样式。由于这可能不是预期的效果,因此最好使用style
直接属性
div.style.height = '100px';
div.style.width = '100px';
div.style.border = '2px solid black';
CSS 属性以短横线形式编写,即用破折号分隔的小写单词。但是,短横线 CSS 属性不能在 JavaScript 样式属性上使用,因为破折号-
用于减法。相反,它们将被替换为对应的驼峰命名法,即第一个单词为小写,所有后续单词均大写。换句话说,而不是text-align
use textAlign
JavaScript 样式属性。
// Make div into a circle and vertically center the text
div.style.borderRadius = '50%';
div.style.display = 'flex';
div.style.justifyContent = 'center';
div.style.alignItems = 'center';
完成以上风格修改后,你的最终效果图styles.html
将显示一个圆圈:
如果要对元素应用许多样式更改,最好的做法是将样式应用到样式表中的单独类,然后将该类添加到元素中。但是,在某些情况下,修改内联样式属性是必要的或更直接的。
HTML 元素通常以属性的形式分配有附加信息。属性可能由名称/值对组成,一些最常见的属性是class
and style
.
在本教程中,您学习了如何使用纯 JavaScript 访问、修改和删除 DOM 中 HTML 元素的属性。您还学习了如何在元素上添加、删除、切换和替换 CSS 类,以及如何编辑内联 CSS 样式。如需更多阅读,请查看有关的文档属性在 Mozilla 开发者网络上。