w3resource

JavaScript: Set the background color of a paragraph

JavaScript DOM: Exercise-3 with Solution

Write a JavaScript program to set the background color of a paragraph.

Sample Solution: -

HTML Code:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Set the background color of a paragraph</title>
</head>
<body>
<input type="button" value="Click to set paragraph background color" onclick="set_background()">
<p>w3resource JavaScript Exercises</p>
<p>w3resource PHP Exercises</p> 
</body>
</html>

JavaScript Code:

function set_background() {
 docBody = document.getElementsByTagName("body")[0];
  //Get all the p elements that are descendants of the body
  myBodyElements = docBody.getElementsByTagName("p");
// get the first p elements
  myp1 = myBodyElements[0];
  myp1.style.background = "rgb(255,0,0)";
// get the second p elements
  myp2 = myBodyElements[1];
  myp2.style.background = "rgb(255,255,0)";
}

Sample Output:

javascript-dom-exercise-3

Flowchart:

Flowchart: JavaScript - Set the background color of a paragraph.

Live Demo:

See the Pen javascript-dom-exercise-3 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to get the values of First and Last name of the following form.
Next: Write a JavaScript function to get the value of the href, hreflang, rel, target, and type attributes of the specified link.

What is the difficulty level of this exercise?



JavaScript: Tips of the Day

getList function

const getList = ([x, ...y]) => [x, y]
const getUser = user => { name: user.name, age: user.age }

const list = [1, 2, 3, 4]
const user = { name: "Owen", age: 23 }

console.log(getList(list))
console.log(getUser(user))

The getList function receives an array as its argument. Between the parentheses of the getList function, we destructure this array right away. You could see this as:

[x, ...y] = [1, 2, 3, 4]
With the rest parameter ...y, we put all "remaining" arguments in an array. The remaining arguments are 2, 3 and 4 in this case. The value of y is an array, containing all the rest parameters. The value of x is equal to 1 in this case, so when we log [x, y], [1, [2, 3, 4]] gets logged.
The getUser function receives an object. With arrow functions, we don't have to write curly brackets if we just return one value. However, if you want to return an object from an arrow function, you have to write it between parentheses, otherwise no value gets returned! The following function would have returned an object:
const getUser = user => ({ name: user.name, age: user.age })
Since no value gets returned in this case, the function returns undefined.

Ref: https://bit.ly/3jFRBje