0

I am trying to get the content inside of a by the class name but i get undefined when i run the script... what am i doing wrong?

    <!DOCTYPE html>
<html>
<body>

<td class="a-size-base">B000FNFSPY</td>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {

var x = document.getElementsByClassName("a-size-base").innerText;
    document.write(x)
}
</script>

</body>
</html>
Kelly
  • 93
  • 9

4 Answers4

1

Here is the solution:

<!DOCTYPE html>
<html>
  <body>
   <div class="a-size-base">B000FNFSPY</div>
   <button onclick="myFunction()">Try it</button>
 <script>
   function myFunction() {
    var x = document.getElementsByClassName("a-size-base")[0].innerText;
    document.write(x)
   }
 </script>
 </body>
</html>

When the browser compiles with td then since table tag is not used and hence it renders it as it is and the td tag is omitted.

Kinshuk Lahiri
  • 1,468
  • 10
  • 23
0

You misused <td> tag, it has to be put inside a table. Or it will not be rendered into DOM with webkit or most browsers.

Tested in Chrome. See, <td> is not there.

And getElementsByTagName returns an array. But you went wrong in the first step, so it's not even get here yet.

enter image description here

function myFunction() {
    var x = document.getElementsByClassName("a-size-base");
    document.write(x);
}
    <!DOCTYPE html>
<html>
<body>

<td class="a-size-base">B000FNFSPY</td>

<button onclick="myFunction()">Try it</button>

</body>
</html>
Val
  • 21,938
  • 10
  • 68
  • 86
0

You can do this way:

<!DOCTYPE html>
<html>
<body>

<div class="a-size-base">B000FNFSPY</div>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {

var x = document.getElementsByClassName("a-size-base");
    document.write(x[0].innerHTML)
}
</script>

</body>
</html>
Asif Raza
  • 3,435
  • 2
  • 27
  • 43
0

The getElementsByClassName method returns an array-like collection of elements. You should loop through the items to access their innerText.

Nekomajin42
  • 638
  • 1
  • 6
  • 20