Home > other >  How to set a span in JS instead of making a alert
How to set a span in JS instead of making a alert

Time:04-29

Kind of a newbie to this but I have followed a totorial on a memory game as an attempt to understand the syntax of JS but am stuck on making the round result print in a instead of showing up as a alert here is a codepen here.

how can I print round in a <span> <!-- result here--> </span> rather than like this alert("result")

How can I make it set to a span instead of being an alert?

CodePudding user response:

Browsers parse HTML into a tree of objects called Document Object Model (DOM). Using JavaScript you can query the DOM to get individual nodes, and then change them.

To get your span, you would typically use document.getElementById or document.querySelector (there are other functions that can fetch collections of related nodes, like document.getElementsByClassName or document.querySelectorAll). The former identify nodes by the property named in the method name (ID, or class name, respectively); the latter ones use CSS selectors. (All of the getElement... functions can be replicated using the newer querySelector and querySelectorAll interface, though you have to know how to use CSS selectors. I almost never use getElement... functions any more.) There are also functions that use XPath, though this is a bit more advanced subject.

Once you have the node, you can change its content using e.g. .textContent or .innerHTML properties, the former being for plain text, the latter for HTML.

For example, if this is the only span on the page, this suffices:

document.querySelector('span').textContent = "Result";
<span></span>

If on the other hand you have more of them, you would need some way to target the correct one. I will also demonstrate how you can style it using HTML:

const node = document.querySelector('#result_goes_here');
node.innerHTML = "<strong>Result</strong> in bold!";
<span id="result_goes_here"></span>

CodePudding user response:

If you are trying to add the result inside the HTML SPAN and not in the alert box. You can do it something like this:

document.getElementById("span_ID").innerHTML = the_variable_result_here;

Hope that helps!

  • Related