Functions for working with a DOM element in JavaScript

Now we will learn how to make helper functions that perform any operations with the DOM. For example, let's make a function that takes the element's id as the first parameter, and the element's text as the second, and will set the new text for that element.

Here is the described function:

function setText(id, text) { let elem = document.getElementById(id); elem.textContent = text; }

Let's try out its work. Let's say we have two paragraphs:

<p id="elem1"></p> <p id="elem2"></p>

Let's change the text of these paragraphs using the function we created:

setText('elem1', 'text1'); setText('elem2', 'text2');

Modify the function I created so that it takes as a parameter not the id of the element, but an arbitrary CSS selector.

Make the setAttr function that will change the element's DOM attribute. Let the function take the element selector as the first parameter, the attribute name as the second, and its new value as the third.

enru