0

I want to change the content of h1 by using if statement in Javascript, is there a way to make Javascript variable read the content of h1?

<body>

    <h1 id="tae">bebe</h1>

    <script>
        var baby = document.getElementById('tae');

        if (baby == 'bebe') {
            document.getElementById('tae').innerHTML = 'my moon';
        }
    </script>

</body>
Ame Suzuki
  • 59
  • 4
  • So you’re correctly _setting_ the contained text here: `document.getElementById('tae').innerHTML = 'my moon'`. But for whatever reason you’re _getting_ the contained text _without_ the `.innerHTML`?! By the way, the _recommended_ approach is to use the [`textContent`](//developer.mozilla.org/en/docs/Web/API/Node/textContent) property in both cases. – Sebastian Simon Nov 22 '22 at 07:32

1 Answers1

1

You need to use innerText to do it

var baby = document.getElementById('tae').innerText;

<body>

    <h1 id="tae">bebe</h1>

    <script>
        var baby = document.getElementById('tae').innerText;
        // textContent also works
        //var baby = document.getElementById('tae').textContent;

        if (baby == 'bebe') {
            document.getElementById('tae').innerHTML = 'my moon';
        }
    </script>

</body>
flyingfox
  • 13,414
  • 3
  • 24
  • 39
  • 2
    [`textContent`](//developer.mozilla.org/en/docs/Web/API/Node/textContent) makes more sense than [`innerText`](//developer.mozilla.org/en/docs/Web/API/HTMLElement/innerText); it’s more intuitive and doesn’t do any CSS processing. – Sebastian Simon Nov 22 '22 at 07:36
  • textContent is way faster then innerText. However, a Regex would have been simpler in this case. – tacoshy Nov 22 '22 at 07:55