I am working on a project that collects a piece of information from a website and returns that value in an HTML Document.
Here is what my HTML file looks like:
script type="text/javascript" src="website_fetch.mjs"></script>
<section>
<h2>Info on Google here</h2>
<ul>
<article is= "site-status" name="Google" info = NEED RETURN VALUE FROM SCRIPT ABOVE ></article>
How can I get the returned value from this script? In the JS file, there is a return statement that I need to set equal to info in the <article> tag.
Any help greatly appreciated.
Alter the script so that it selects the article tag you're interested in and populates the attribute. For example, if you have
// website_fetch.mjs
export const getGoogleInfo = async () => {
// implementation goes here
return someInfo;
};
you can change it to
// website_fetch.mjs
export const getGoogleInfo = async () => {
// implementation goes here
return someInfo;
};
getGoogleInfo()
.then((result) => {
document.querySelector('article[is="site-status"]').setAttribute('info', result);
});
// .catch(handleErrors); // don't forget this part - don't ignore errors
Your getGoogleInfo is asynchronous, so you have to wait for its Promise to resolve to a value before inserting the info.
But there's another problem. Your HTML is invalid. An <article> cannot be a child of a <ul>. An unordered list can only have children that are list items (<li>). Fix your HTML so that it's valid, so that none of your markup gets dropped or parsed incorrectly.
Live demo:
// this is just to show that the article's info attribute is as desired:
setTimeout(() => {
console.log(document.querySelector('section').innerHTML);
}, 1000);
<script type="module">
export const getGoogleInfo = async () => {
// implementation goes here
return 'someInfo';
};
getGoogleInfo()
.then((result) => {
document.querySelector('article[is="site-status"]').setAttribute('info', result);
});
</script>
<section>
<h2>Info on Google here</h2>
<article is="site-status" name="Google" info=N EED RETURN VALUE FROM SCRIPT ABOVE></article>
</section>