Home>

I want to change the html display using getElementsByTagName, getElementById, getElementsByClassName.

Error message

When clicked, only the first getElementsByTagName is changed.

### Corresponding source code
<html>
<head>
<meta charset = "utf-8">
<meta robot = "noindex">
</head>
<body>
    <div>
    <div>
        <p>aa Corporation</p>
    </div>
    <span>Aa</span>
    <div></div>
    <button type = "button" onclick = "clicker ();"></button>
    </div>
    <script>
        function clicker () {
            var changeName = document.getElementsByTagName ('p');
            changeName [0] .innerHTML = "aa corporation";
            var changeId = document.getElementById ('corp'). value;
            changeId [0] .innerHTML = "OO business";
            var changeClass = document.activeElementByClassName ('class');
            changeClass [0] .innerHTML = "Operating";
        }
    </script>
</body>
</html>

Enter the language name here
html, Javascript
`` `

Tried Supplemental information (FW/tool version etc.)
  • Answer # 1

    Since there was a mistake in the script

    function clicker () {
                var changeName = document.getElementsByTagName ('p');
                changeName [0] .innerHTML = "aa corporation";
                var changeId = document.getElementById ('corp');
                changeId.innerHTML = "OO business";
                var changeClass = document.getElementsByClassName ('class');
                changeClass [0] .innerHTML = "Operating";
            }


    Try changing to.

  • Answer # 2

    There is already a good answer regarding proper use, so another idea
    Example of processing with querySelector

    document.querySelector ('p'). textContent = "xxx";
    document.querySelector ('# corp'). textContent = "yyy";
    document.querySelector ('. class'). textContent = "zzz";

  • Answer # 3

    .value is basically used to get the value of the input tag.
    For example, it cannot be used when you want to get the text in the div tag.
    In this case, since the text replacement inside is not done separately, the element itself is fine.
    What was .activeElementByClassName?
    It looks good with getElementsByClassName.

    Based on

    , it looks like the code that realized what you want to do ↓

    function clicker () {
                var changeName = document.getElementsByTagName ('p');
                changeName [0] .innerHTML = "aa corporation";
                var changeId = document.getElementById ('corp');
                changeId.innerHTML = "OO business";
                var changeClass = document.getElementsByClassName ('class');
                changeClass [0] .innerHTML = "Operating";
            }

  • Answer # 4

    getElementByIdis singular, so only one is returned, so[0]does not need to be retrieved is. Since[0]becomesundefined, it seems that there is an error after that.