Get the DOM element to be modified through jQuery, and then modify the attributes, classes and styles through JavaScript methods
Today in This article will share how to further change the dom by modifying the style, class and attributes of the HTML element node. It has certain reference value and I hope it will be helpful to everyone.
【Recommended courses: JavaScript Tutorial, jQuery Tutorial】
Find the element to be selected
We can select and modify elements in the DOM through jQuery. jQuery simplifies the process of selecting one or more elements and applying changes to all elements simultaneously
Among them, document.querySelector() and document.getElementById() are the methods used to access individual elements.
Example:
function myFunction() { document.querySelector(".example").style.backgroundColor = "pink"; }
Rendering:
Accessing a single element, we can change the content of the text
document.querySelector(".example").textContent="点击文本发生变化";
Rendering:
Modify attributes
Attributes are values that contain additional information about an HTML element. They usually consist of name/value, depending on the element.
In JavaScript, we have four methods to modify element attributes:
Method | Description | Example |
Returns a true or false Boolean value | element.hasAttribute('href' ); | |
Returns the value of the specified attribute or null | element.getAttribute('href'); | |
Add or update the value of the specified attribute | element.setAttribute('href', 'index.html'); | |
Remove attributes from elements | element.removeAttribute('href'); |
方法/属性 | 描述 | 例 |
className | 获取或设置类值 | element.className; |
classList.add() | 添加一个或多个类值 | element.classList.add('active'); |
classList.toggle() | 在元素中切换类名 | element.classList.toggle('active'); |
classList.contains() | 检查类值是否存在 | element.classList.contains('active'); |
classList.replace() | 用新的类值替换现有的类值 | element.classList.replace('old', 'new'); |
classList.remove() | 删除类值 | element.classList.remove('active'); |
例:
.demo1{ width:100px; height:100px; background-color: pink; } .demo2{ width:200px; height:200px; background-color:skyblue; } function demo(){ var p =document.getElementsByTagName("p")[0]; p.classList.toggle("demo2"); }
效果图:
总结:以上就是本篇文章的全部内容了,希望对大家有所帮助。
The above is the detailed content of How to modify properties, classes and styles in the DOM. For more information, please follow other related articles on the PHP Chinese website!