I’m new in learning JavaScript. Just for some test I built this function and call it and assign a variable in it to complete result. Is there any way use function like this example?
Here I wanna just pass #country in dom(i) function. so it should be getElementById("maid"), and after call it, assign = maid to put this maid variable after innerHTML =
I’m wondering is it possible to write JavaScript function like this way?
var maid = "Made In Yiappa";
function dom(i) {
var docs = document.getElementById(i).innerHTML;
return docs;
}
dom("country") = maid;
<p> The result is: <span id="country"></span> </p>
>Solution :
You must pass it as argument to that function:
var maid = "Made In Yiappa";
function dom(elementId, txt) {
document.getElementById(elementId).innerHTML = txt;
}
dom("country", maid);
<p> The result is: <span id="country"></span> </p>
If you want to use a Closure (learn more on developer.mozilla.org):
Closures are one of the most powerful features of JavaScript.
JavaScript allows for the nesting of functions and grants the inner
function full access to all the variables and functions defined inside
the outer function (and all other variables and functions that the
outer function has access to).
First assign the function to a variable, then invoke that variable as function and pass in it two arguments.
var maid = "Made In Yiappa";
var dom = function dom(i, txt) {
document.getElementById(i).innerHTML = txt;
}
dom("country", maid);
<p> The result is: <span id="country"></span> </p>