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
First of all, getElementById is a method that belongs to the document object. So, you need to do
document.getElementById()
ordocument.getElementsByTagName()
for it to work.If you want to extract the content of the span, I would suggest this to make it easier.
<span id="theSpan">2</span>
const spanTag = document.getElementById("theSpan").innerHTML
andlet pTag = document.getElementById("placeSpanVAR")
I left a snippet for you and it works! Have a good one
`
There are some mistakes in the code. Here is the updated code. Try that:-
Remember that, getElementById or getElementsByTagName, are methods of document interface. So you have to write document. with these methods.