The DOM paragraph object is used to represent the HTML <p> element. The p element is accessed by getElementById().
Syntax:
document.getElementById("id");
Where ‘id’ is the ID assigned to the p tag.
The below programs illustrate the p object:
Property Values
- align: It is used to set or return the alignment of the paragraph element.
Example 1: In the below program the paragraph element is assigned the id = “s”. With the click of the button, the paragraph element is accessed and the color of the paragraph text is changed.
HTML
<!DOCTYPE html>
< html >
< body >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< h2 >DOM paragraph Object</ h2 >
< button onclick = "Geeks()" >
Click Here
</ button >
< p id = "s" >
A computer science
portal for geeks.
</ p >
< script >
function Geeks() {
let txt = document.getElementById("s");
txt.style.color = "green";
}
</ script >
</ body >
</ html >
|
Output:
Example 2: A paragraph Object can be created by using the document.createElement method. In the below program, we create a paragraph element and append a text node to it.
HTML
<!DOCTYPE html>
< html >
< body >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< h2 >DOM paragraph Object</ h2 >
< button onclick = "Geeks()" >
Click Here!
</ button >
< br >< br >
< div id = "p" ></ div >
< script >
function Geeks() {
let txt = document.createElement("P");
let t = document.createTextNode(
"A computer science portal for geeks.");
txt.appendChild(t);
document.getElementById("p").appendChild(txt);
}
</ script >
</ body >
</ html >
|
Output:
Supported Browsers:
- Google Chrome
- Mozilla Firefox
- Edge
- Safari
- Opera
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!