I'm new in learning JavaScript. Just for some test I built this function and call it and assign a variable in it to a complete result. Is there a way use the function like this example?
Here I want to just pass #country in the dom(i) function. So it should be getElementById("maid"), and after calling 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>
You must pass it as an 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>
You can’t assign a value to the result of a function call. You need to pass it as a function argument.
var maid = "Made In Yiappa";
function dom(i, text) {
document.getElementById(i).innerHTML = text;
}
dom("country", maid);
<p> The result is: <span id="country"></span> </p>
The key issue is that you're returning the value of the innerHTML property from the function but you can't then assign a string to it because innerHTML can only be set when it's attached to an element.
querySelector maybe a better method choice. You can then pass in your #country selector as you mentioned in your question.
So, we can remove some of the functionality from the function, and just have it return the element using the selector. Then we can assign main to the innerHTML of that returned element (although innerText might be more appropriate).
var maid = 'Made In Yiappa';
function dom(selector) {
return document.querySelector(selector);
}
dom('#country').innerText = maid;
<p> The result is: <span id="country"></span> </p>