Is it possible to modify a nested h2 element using getElementsByTagName?

Looking to dynamically change the text of an h2 element nested within a div using JavaScript? No problem! Let's dive into how we can achieve this without altering the HTML file directly.

Here's the HTML structure we're working with:

<div id="button">
    <h2>Click me</h2>
</div>

I've experimented with both getElementsByTagName and firstElementChild methods, but only firstElementChild seems to do the trick.

The following code snippet demonstrates that firstElementChild works as expected:

window.onload = function pageLoaded(){
    const button = document.getElementById("button");
    const clickMe = button.firstElementChild;

    button.onclick = changeText;
    function changeText(){
        clickMe.innerHTML = "You clicked me";
        console.log(clickMe);
    }
}

However, when utilizing getElementsByTagName, the update is not reflected on the webpage:

window.onload = function pageLoaded(){
    const button = document.getElementById("button");
    const clickMe = button.getElementsByTagName("h2");

    button.onclick = changeText;
    function changeText(){
        clickMe.innerHTML = "You clicked me";
        console.log(clickMe);
    }
}

Although the innerText property gets updated in the HTMLCollection, the changes are not visible on the webpage itself. Why does this happen?

Additionally, why does firstElementChild only work properly when wrapped inside the window.onload event listener? Removing it results in a "cannot get properties of null" error for firstElementChild.

Answer №1

The getElementsByTagName function
will give you back an HTMLCollection. Make sure to retrieve the first element from this collection:

window.onload = function(){
    const button = document.getElementById("button");
    const heading = button.getElementsByTagName("h2")[0];

    button.onclick = changeText;
    function changeText(){
        heading.innerHTML = "Button Clicked!";
        console.log(heading);
    }   
}
<div id="button>
    <h2>Click here</h2>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"MongoDB fails to save changes when attempting to remove an item from an updated

I've been using Angular Fullstack for a web application. When I send my data using $http.post(), I include the following object: { title: "Some title", tags: ["tag1", "tag2", "tag3"] } However, when I edit the object and try to update it with $http ...

Using Laravel Livewire to make text vanish by setting a time limit for the flash message

I've developed a feature using Laravel Livewire that triggers a modal to show up whenever a user successfully subscribes or volunteers to join my website. I attempted to implement code that would delay the modal, but instead of making text disappear a ...

Using dropzone.js on multiple files in a single webpage

Is it feasible to incorporate multiple dropzone elements on one webpage instead of having numerous file uploads on a single dropzone element? It appears that dropzone fails to trigger after the selection dialog box when there are several elements, each wi ...

Ways to swap out element within ViewContainerRef in Angular

I am currently expanding my knowledge of Angular and I have encountered a challenge regarding dynamically creating components and swapping them within a single container. Here is the setup: <ng-container #container></ng-container> Here are the ...

Troubleshooting: Issues with TextureLoader causing image rendering failure in three.js

Here is the approach I take to incorporate an image using three.js - rendererModule.addImage = function (primitive){ var self = this; var textureLoader = new THREE.TextureLoader(); console.log("This is step 1"); textureLoader.load("image/m ...

Every time I attempt to execute this piece of code in "node.js", an error pops up

const express = require('express'); const request = require('request'); const bodyParser = require('body-parser'); const https = require('https'); const app = express(); app.use(express.static('public')); ...

Tips for sending refs to components that load lazily

Hey everyone, I'm currently working on passing refs to a lazy load component but running into an issue where I'm receiving null instead of {current: null}. Can someone help me identify where I might be making a mistake? 'use client'; im ...

Get rid of the upgrade button feature from TinyMCE editor

Recently, I started using tinymce in inline mode and it's a new tool for me. I have managed to adjust the text field input to my liking with just a few editing buttons. However, I am stuck trying to figure out how to get rid of the "Upgrade" button fr ...

Is it possible for a dash in a GET variable name to cause issues with req.query in NodeJS Express?

I am currently developing a GET endpoint in Node.js using Express to handle the following variable: ?message-timestamp=2012-08-19+20%3A38%3A23 However, I am facing difficulty accessing it through req.query. Whenever I try to access req.query.message-time ...

How to adjust the timezone settings in PHPMyAdmin on a shared server platform

I'm having trouble changing my timezone to India on my shared server database. I've tried everything but can't seem to get it to work. My website is built using PHP Codeigniter The contact us page on my site saves all inquiry details to my ...

Sending an AJAX request to submit a form and receiving a response

I am in the process of developing a Rails application and I am seeking a way to submit a form using Ajax. This functionality is crucial as I want the form submission to occur without causing a full page reload. Initially, I tried using form_remote_tag but ...

What is the best way to slide a Bootstrap 4 modal dialog to the right when closing, utilizing CSS or JavaScript

I have successfully added a CSS animation to my Bootstrap modal that slides in from the right when opening, which looks great. However, I am looking for a way to slide it back to the right when a custom close button is clicked, instead of just hiding it wi ...

Retrieve specific information from checkboxes within a form

I'm working on a form that includes multiple checkboxes populated with data from a JSON file using ng-repeat. After submitting the form, I need to retrieve the data from the checked checkboxes. How can I accomplish this in my controller after the form ...

In Javascript, what type of value does a Sproutcore query to a database return?

queryNote = SC.Query.local('Tree.Note', "categoryId = {categoryId}", { categoryId: this.get('guid'), orderBy: "name ASC" }); var arrayCategory = Tree.store.find(queryTree); What is the dat ...

Is there a way to extract information from an uploaded file in JavaScript without having to actually submit the file?

Looking for a way to extract data from a user uploaded file using Javascript without page submission? The goal is to process this data to provide additional options in a form on the same page. Any assistance with this would be highly appreciated. ...

Send a stored image from state to Express JS as a static image

Currently, I have a view where users can upload an image and preview it on the page. In addition to this, there is also a form with two text inputs. When the form is submitted, the text inputs are sent to my Express JS server using axios to be displayed on ...

Unable to retrieve grade from API JSON

After making a request to the API, I received the following data results: "tabledata": [ { "itemname": { "class": "level1 levelodd oddd1 b1b b1t column-itemname", "colspan": 7, " ...

leveraging a callback function alongside the useState hook

I'm facing an issue with the change() function. My goal is to call the filteredData() function after the setState operation is completed. Typically, I would use a callback function for this task, but useState doesn't support callbacks. Using useE ...

Update the text content when clicked in React

For the onClick event, I am attempting to edit the entered text using the enableEdit function. My goal is to trigger the function when double-clicking on the entered text. Here is a snippet of my code: class App extends React.Component { const ...

Tips for adding a value to a specific object in an array

I am currently utilizing Vue along with Vuetify's v-data-table to display some data. Everything is functioning as expected, but I also need to incorporate data from another API. Therefore, I am looking for a way to add items to an array of objects. ax ...