Home >Web Front-end >Front-end Q&A >javascript set document
JavaScript is a powerful programming language that can embed code directly in web pages to change the appearance and behavior of web pages. In JavaScript, the document object represents the entire web page, and we can use it to dynamically modify the content and structure of the web page.
In this article, we will discuss some basic settings and usage of document objects in JavaScript.
1. Get the element
To modify the elements in the web page, you must first get the reference of the element. In JavaScript, you can get an element through the following methods:
var elem = document.getElementById("my-element");
var elems = document.getElementsByTagName("p");
var elems = document.getElementsByClassName("my-class");
var elem = document.querySelector(".my-class"); var elems = document.querySelectorAll("p");
2. Modify element attributes and content
After obtaining the element reference, you can use JavaScript to modify the element's attributes and content. The following are some common operations:
elem.innerHTML = "Hello, world!";
elem.style.color = "red"; elem.style.backgroundColor = "blue";
elem.className = "my-class";
elem.setAttribute("href", "http://www.example.com"); elem.removeAttribute("target");
3. Adding and deleting elements
JavaScript can also dynamically add and delete elements. Here are some examples:
var newElem = document.createElement("p"); newElem.innerHTML = "This is a new paragraph."; document.body.appendChild(newElem);
document.body.removeChild(elem);
4. Event handler
Event handler in JavaScript is used to respond to user operations or browser events. Here are some examples:
elem.addEventListener("click", function() { alert("Clicked!"); });
elem.removeEventListener("click", listener);
5. Summary
The document object in JavaScript can help us dynamically modify the content and structure of web pages so that users can interact with web pages. This article introduces some common usage methods, including getting elements, modifying element properties and content, adding and removing elements, event handlers, etc. I hope this content can help you better use JavaScript to display excellent results on web pages.
The above is the detailed content of javascript set document. For more information, please follow other related articles on the PHP Chinese website!