0

I'm trying to create an online calculator, using a table, with a tag that will have an output that changes. The output is the result of whatever math function is used on the calculator. So if someone puts in 5*5, the th should show 25. I tried using a variable, output, in javascript, and then using document.getElementsByTagName("th").innerHTML(output), to have it changing, but that didn't work. Then I tried the same command without a variable, and instead just directly inserting a string in the innerHTML and it still wasn't working. I also tried write(), but that didn't work either. Any ideas on what I can try?

This is my table (the id's and classes are just some style attributes in my css file):

<table class="center" style = "width:20%">
    <tr>
        <th colspan="4" id = "final">0</th>
    </tr>
    <tr id = "opRow">
        <td>+</td>
        <td>-</td>
        <td>x</td>
        <td>/</td>
    </tr>
    <tr class = "dataRow">
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td rowspan = "4" id = "eqBut">=</td>
    </tr>
    <tr class = "dataRow">
        <td>4</td>
        <td>5</td>
        <td>6</td>
    </tr>
    <tr class = "dataRow">
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr class = "dataRow">
        <td style = "width:26%" id = "acBut">ac</td>
        <td>0</td>
        <td>.</td>
    </tr>
</table>

2 Answers 2

2

getElementsByTagName() returns an array and so you'll have to reference it like this:

document.getElementsByTagName("th")[0]

assuming that you only have 1 th tag on your current page.

plus innerHTML is a property of an element and not a method, so you'll have to rewrite:

document.getElementsByTagName("th")[0].innerHTML = output

Also, your current implementation should be throwing some errors in your browser console log please do check it out.

Sign up to request clarification or add additional context in comments.

Comments

1

Method / function

getElementsByTagName

is returning an array with all available tags from your html, then you've only 1 th in your table so is result the th tag from your table is first [0], now use method mention to select th tag and select first element [0]

innerHTML - used to rewrite data as I know

and use it to rewrite cell.

So use that :

document.getElementsByTagName("th")[0].innerHTML = 52;

To check if is working try this :

document.addEventListener("DOMContentLoaded", function(){
    document.getElementsByTagName("th")[0].innerHTML = 52;
});

Well, I hope that you understand what I want to say. Thanks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.