Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
Don’t repeat yourself
Note that as we are in the process of solving the task, we often repeat the same operations: we create elements with document.createElement()
, we add classes to it using element.classList.add()
, and in some cases also text content using element.textContent
. It’s time to add the repeating code to the function so that you don’t have to write many similar lines of code each time.
Declare a function that will accept three input strings: tag name (tagName
), class name (className
) and text content (text
) of the element. Inside it we’ll create an element with a class and text, and then take it out.
Not all elements have text content, that’s why let’s make sure that we can call the function not with three, but with two parameters. JavaScript alone allows us to do this. But we need to provide a check to see if the third parameter is present. We’ll add text to the element using textContent
only if parameter text
exists.
How to check if a parameter is present? If the parameter wasn’t transferred to the function, its value inside the function will be undefined
, that is, it’s not defined. Value undefined
is converted to logical value false
, therefore, such a simple check is enough:
var createCard = function (required, optional) {
if (optional) {
// actions with optional
}
}
// The function will work, but the actions
// with optional will not be executed
createCard('Required argument');
// The function will work and operations with optional are executed
createCard('Required argument', 'Optional argument');
And what if the argument is transferred? First, it will not equal undefined
. Secondly, inside the parentheses operator, the program will get the value of this parameter and convert it into a logical type. As you know from the “Conditions” course, strings can act as conditions. An empty string is converted to false
, and a non-empty one to true
. That is, text content will be added to the element only when we transfer a non-empty string as the last argument. That is exactly what we need.
- index.html
- style.css
- script.js
Thanks! We’ll fix everything at once!
Click inside the mini browser to put the focus in this window.
- At the beginning of the code, declare a function
makeElement
with parameterstagName
,className
,text
. - In the body of the function, create a DOM element with tag name
tagName
and assign it to theelement
variable. - Add class
className
to the element. - Add a check to see if the
text
parameter is available. If the check is successful, add text contenttext
toelement
. - Return
element
from the function.
Comments