0

Codepen: https://codepen.io/bgbs/pen/XaNOgM

What I'm trying to do is have the JavaScript select a specific word in td, and wrap it with span for further styling. But it doesn't want to work for some reason. Any ideas?

<style>
  .big {
    font-size: 55px;
  }
</style>
<script>
  function chng() {
    var text = document.getElementByTagName('td').innerHTML;
    var text2 = text.replace('Germany','<span class="big">Germany</span>');
    document.getElementByTagName('td').innerHTML = text2;
  }
</script>

<body>
  <table>
    <tr>
      <td>Brazil - England - Germany</td>
    </tr>
  </table>
  <button onclick="chng()">Try it</button>
</body>
Makyen
  • 31,849
  • 12
  • 86
  • 121
user5248
  • 347
  • 1
  • 3
  • 21
  • 1
    There's no such a method: `document.getElementByTagName`. – Teemu Aug 04 '17 at 23:20
  • Related: [Change matching words in a webpage's text to buttons](https://stackoverflow.com/a/40576258) – Makyen Aug 05 '17 at 08:46
  • Possible duplicate of: [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/q/10693845) – Makyen Aug 05 '17 at 09:00

1 Answers1

1

try this one:

function chng(){
    var text = document.getElementsByTagName('td')[0].innerHTML;
    var text2 = text.replace('Germany','<span class="big">Germany</span>');
    document.getElementsByTagName('td')[0].innerHTML = text2;
}

You misspelled getElementsByTagName(). It returns HTMLCollection and you need to get the first element, so document.getElementsByTagName('td')[0].

curveball
  • 4,320
  • 15
  • 39
  • 49
  • Whoa! That's awesome. What does [0] supposed to do? – user5248 Aug 04 '17 at 23:11
  • 1
    it takes the first element of HTMLCollection you got by calling `getElementsByTagName()`. This function returns a collection of many elements, not a single one. `[0]` specifies the exact element you want to take. – curveball Aug 04 '17 at 23:12