Home > Article > Web Front-end > Use JavaScript functions to manipulate DOM elements and modify styles
Use JavaScript functions to manipulate DOM elements and modify styles
JavaScript is a powerful programming language that can be used to manipulate the DOM (Document Object Model) in HTML pages ) element and modify the style. In this article, we'll learn how to use JavaScript functions to perform these tasks and provide some concrete code examples.
getElementById
function to get the DOM element by its ID. For example: var element = document.getElementById("myElement");
innerText
attribute or the textContent
attribute to modify it. These two properties work very similarly, the difference lies in the way they treat HTML tags. element.innerText = "新的文本内容";
style
attribute. For example, the following code will modify the background color of the element to red: element.style.backgroundColor = "red";
classList
attribute to achieve this. The add
function is used to add a class name, and the remove
function is used to remove a class name. element.classList.add("myClass"); element.classList.remove("myClass");
createElement
function to create a new element, and then use the appendChild
function to add it to another element. var newElement = document.createElement("div"); newElement.innerText = "新创建的元素"; parentElement.appendChild(newElement);
addEventListener
function. Here is an example of an alert box popping up when the button is clicked. var button = document.getElementById("myButton"); button.addEventListener("click", function() { alert("按钮被点击了"); });
The above are some examples of using JavaScript functions to manipulate DOM elements and modify styles. By using these functions flexibly, we can achieve many interesting special effects and interactive effects. Hope this article helps you!
The above is the detailed content of Use JavaScript functions to manipulate DOM elements and modify styles. For more information, please follow other related articles on the PHP Chinese website!