skip to Main Content

I have the following code example and looking to extract the contents of the span element "(2)" and insert it into an element id using JavaScript. Here is the HTML code example:

function countTest() {
  let span = getElementById("spanID").getElementsByTagName('span')[0].innerHTML
  document.getElementById("placeSpanVAR").innerHTML = span;
}
<script src="countTest.js"></script>

<tbody id="spanID">
  <tr>
    <td colspan="100" nowrap="nowrap" class="ms-gb">
      <a href="javascript:" onclick=""></a>
      <span>(2)</span>
    </td>
  </tr>
</tbody>
<br>
<p id="placeSpanVAR"></p>

<body onload="countTest()">

Can someone help me understand why this is not working and perhaps what might?

2

Answers


  1. First of all, getElementById is a method that belongs to the document object. So, you need to do document.getElementById() or document.getElementsByTagName() for it to work.

    If you want to extract the content of the span, I would suggest this to make it easier.

    1. Give the span you want to extract the content from an "id". So you can query for it in the easiest way possible <span id="theSpan">2</span>
    2. Query for the span and query for the p tag you want to insert the html on. const spanTag = document.getElementById("theSpan").innerHTML and let pTag = document.getElementById("placeSpanVAR")
    3. Then just assign the HTML content of spanTag to pTag `pTag = span

    I left a snippet for you and it works! Have a good one

    const spanContent = document.getElementById("theSpan").innerHTML
    let p = document.getElementById("placeSpanVAR")
    p = spanContent
    console.log(p)
    <tbody id="spanID">
        <tr>
            <td colspan="100" nowrap="nowrap" class="ms-gb">
                <a href="javascript:" onclick=""></a>
                    <span id="theSpan">(2)</span>
            </td>
        </tr>
    </tbody>
    <br>
        <p id="placeSpanVAR"></p>

    `

    Login or Signup to reply.
  2. There are some mistakes in the code. Here is the updated code. Try that:-

    function countTest() {
      let span = document.getElementById("spanID").getElementsByTagName("span")[0].innerHTML;
      document.getElementById("placeSpanVAR").innerHTML = span;
    }
    <script src="countTest.js"></script>
    <body onload="countTest()">
    <table>
    <tbody id="spanID">
      <tr>
        <td colspan="100" nowrap="nowrap" class="ms-gb">
          <a href="javascript:" onclick=""></a>
          <span>(2)</span>
        </td>
      </tr>
    </tbody>
    </table>
    <br>
    <p id="placeSpanVAR"></p>
    
    </body>

    Remember that, getElementById or getElementsByTagName, are methods of document interface. So you have to write document. with these methods.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search