- How to work with document.body in JavaScript?
- Change the background color of the body using the document.body
- Syntax
- Example
- Add a new element at the end of the body using the document.body
- Syntax
- Example
- What is the HTML DOM Document body Property in JavaScript
- What is the HTML DOM Document “body” Property in JavaScript?
- Conclusion
- About the author
- Talha Saif Malik
- Document.body
- Синтаксис
- Пример
- Примечания
- Спецификации
- Совместимость с браузерами
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
How to work with document.body in JavaScript?
In this tutorial, we will learn how to work with document.body in JavaScript.
Use the document.body property in JavaScript to get the body of the document, i.e., tag. The tag defines the body of the document. The entire content of an HTML document, including all headings, paragraphs, images, hyperlinks, tables, lists, and other elements, is contained in the element.
In an HTML document, there can only be one element.
In this tutorial, we will work with the document.body in JavaScript for −
Change the background color of the body using the document.body
In JavaScript, the document.body contains all of the properties and methods of the body tag. For example, the backgroundColor property specifies the body tag’s background color, which means the whole document’s body color can be modified using this property. The backgroundColor property is available in the style object of the document.body, so we can easily use it in the JavaScript code.
Syntax
document.body.style.backgroundColor = color
In the above syntax, we use the backgroundColor property of document.body to change the background color of the body. The ‘color’ is the color name or the color code.
Example
In the below example, we work with document.body in JavaScript to change the background color of the body. We use a button ‘Change background-color’ associated with a click event. A click handler function executes whenever the user clicks on the button; in this case, it is the ‘changeBg()’ function. This function uses the document.body and backgroundColor property to change the background color of the body.
html> body> h2>Change the background color of the body using the i>document.body/i> in JavaScript/h2> button onclick = "changeBg()"> Change background-color /button> p>Click on the above button to change the background color of the body!/p> script> // 'Change background-color' click event handler funtion function changeBg() // using the document.body document.body.style.backgroundColor = 'rgb(226, 255, 196)' > /script> /body> /html>
Add a new element at the end of the body using the document.body
In JavaScript, we must first create an element using the document to add a new element at the end of the body.createElement() method. Secondly, we need to put some content in the new element, then use the appendChild() method of the document.body, we can add this new element at the end of the body tag.
Syntax
// creating new element const newElement = document.createElement(type) newElement.innerHTML = 'It is a new element' // adding a new element at the end of the body document.body.appendChild(newElement)
In the above syntax, we use the document.createElement() method to create an element, the ‘type’ is the element type user wants to create. The appendChild() method of document.body is used to add a new element at the end of the body.
Example
In the below example, we work with document.body in JavaScript to add a new element at the end of the body. A button ‘Add new element’ is used with a click event that executes a click handler function whenever the user clicks on the button. This function uses the document.body and document.createElement() method to create a new element of type ‘p’ and add it at the end of the body.
html> body> h2>Add a new element at the end of the body using the i>document.body/i> in JavaScript/h2> button onclick = "addNewElement()"> Add new element/button> p>Click on the above button to add a new element at the end of the body!/p> script> // 'Add new element' click event handler funtion function addNewElement() // creating new element const newElement = document.createElement('p') newElement.innerHTML = 'It is a new element' // adding a new element at the end of the body document.body.appendChild(newElement) > /script> /body> /html>
This tutorial taught us how to work with document.body in JavaScript. We have discussed two uses of the document.body. In the first example, we change the background color of the body using the document.body, and in the second example, we add a new element at the end of the body. It is recommended to go through and practice the examples to understand the work of the document.body better
What is the HTML DOM Document body Property in JavaScript
DOM(Document Object Model) comes with the document “body” property in JavaScript that sets the HTML body’s elements as well as returns them. It returns a “body” object that contains the collection of defined HTML elements in the “body” section. Moreover, it is also helpful to set new content for the body elements. Also, it assists the user to modify/customize the HTML document with the help of styling properties.
This post demonstrates the objective and practical implementation of the HTML DOM Document “body” property in JavaScript.
What is the HTML DOM Document “body” Property in JavaScript?
The HTML DOM style “body” is a special kind of property that sets and retrieves the “” elements. It is opposite to the “document.Element” method because the “Element” property accesses the HTML elements.
Syntax (Set the body property)
In this syntax, “newContent” customizes the existing body’s element.
Syntax (Return the body property)
The above-returned syntax does not support any additional parameter.
Let’s use the above-defined syntaxes practically.
Example 1: Applying the Document “body” Property to Get the Body Elements in the Current Document
This example applies the document “body” property to get all the elements present inside the “” tag of the current document.
HTML Code
First, have a look at the stated HTML code:
HTML DOM Document body Property in JavaScript < / h2 >
Display all the body elements of this document: < / p >
Click Here < / button >
< / p >
- The “ ” tag defines the subheading of level 2.
- The “ ” tag specifies the paragraph statement.
- The “ ” tag adds a button with an attached “onclick” event to execute the “demo()” function.
- The last “ ” tag creates an empty paragraph that displays the body elements in the current document.
JavaScript Code
Next, overview the given code:
< script >
function demo ( ) {
const elem = document. body . innerHTML ;
document. getElementById ( «demo» ) . innerHTML = elem ;
}
In the above code snippet:
- The function named “demo()” is defined.
- In its definition, the variable “elem” is declared with a “const” keyword that utilizes the “body” property to get the body elements.
- After that, the “getElementById()” method fetches an added empty paragraph to display the returned HTML body elements in it.
The output first shows the specified HTML elements and then displays the body elements upon the button click.
Example 2: Applying the Document “body” Property to Set the Background Image
The “body” property of the “document” object can also be utilized to customize the body elements such as adding a background image. Let’s see it practically.
HTML Code
Firstly, go through the written HTML code:
Add background image in this document: < / p >
The above code block specifies a paragraph with the stated statement.
JavaScript Code
Now, proceed to the below-stated code:
Here, the “body” property is associated with the “backgroundImage” property to add the specified “url” background image in the whole document.
Output
The output shows that the background image is added to the whole document.
Conclusion
JavaScript uses the document “body” property for setting and getting the HTML body’s elements. It returns all the HTML elements present inside the “” tag. Similarly, it also allows the use of other interactive JavaScript properties that customize the body’s elements. This post provided a brief description of the HTML DOM document “body” property in JavaScript.
About the author
Talha Saif Malik
Talha is a contributor at Linux Hint with a vision to bring value and do useful things for the world. He loves to read, write and speak about Linux, Data, Computers and Technology.
Document.body
Возвращает узел или (en-US) текущей страницы, или null если таких элементов не существует.
Синтаксис
var objRef = document.body; document.body = objRef;
Пример
// в HTML: alert(document.body.id); // "oldBodyElement" var aNewBodyElement = document.createElement("body"); aNewBodyElement.id = "newBodyElement"; document.body = aNewBodyElement; alert(document.body.id); // "newBodyElement"
Примечания
document.body это элемент, который включает в себя содержимое страницы. На страницах с вернётся элемент , а с frameset — элемент .
body может быть заменено, но это удалит все его дочерние элементы.
Спецификации
Спецификация | Статус | Комментарии |
---|---|---|
HTML Living Standard Определение ‘Document.body’ в этой спецификации. | Живой стандарт | |
HTML 5.1 Определение ‘Document.body’ в этой спецификации. | Рекомендация | |
HTML5 Определение ‘Document.body’ в этой спецификации. | Рекомендация | |
Document Object Model (DOM) Level 2 HTML Specification Определение ‘Document.body’ в этой спецификации. | Устаревшая | |
Document Object Model (DOM) Level 1 Specification Определение ‘Document.body’ в этой спецификации. | Устаревшая | Исходное определение. |
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 17 окт. 2022 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.