What is the best way to retrieve the values of document.getElementsByTagName("...") using JavaScript?

Here is a snippet of my code:

const headings = document.getElementsByTagName("h2");
const paragraphs = document.getElementsByTagName("p");

In my HTML file, I have two h2 elements and four p elements.

My goal is to retrieve the entire text content of each element. I attempted to do so with the following code:

const testHeading = headings[0].innerText;

Unfortunately, this approach did not yield the desired result.

If anyone can provide guidance or assistance, it would be greatly appreciated.

Answer №1

let headings = document.getElementsByTagName("h2");
let paragraphs = document.getElementsByTagName("p");

for(let h2 of headings){
    console.log(h2.textContent);
}

for(let p of paragraphs){
    console.log(p.textContent);
}
<h2>Heading 1</h2>
  <p>Paragraph 1</p>


<h2>Heading 2</h2>
  <p>Paragraph 2</p>
  <p>Paragraph 3</p>

Answer №2

To retrieve the value of a Node, you can utilize the textContent method.

var headerNodes = document.getElementsByTagName("h2");
var paraNodes = document.getElementsByTagName("p");

const headerTexts = [...headerNodes].map(node => node.textContent);
const paraTexts = [...paraNodes].map(node => node.textContent);

console.log(headerTexts);
console.log(paraTexts);
<h2>h2 first</h2>
<h2>h2 second</h2>

<p>paragraph 1</p>
<p>paragraph 2</p>
<p>paragraph 3</p>
<p>paragraph 4</p>

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

What is the best way to display pages with different states in ExpressJS?

Here is a code block that I have: var express = require('express'); var newsRouter = express.Router(); newsRouter.get('/:news_param', (req, res) => { let news_params = '/haberler/' + req.params.news_param; req.ne ...

Should one consider employing NodeJS global events through the process object?

Currently, I am using setInterval to periodically query the database and send the results to all connected Socket.IO clients. Here is an example of how I have implemented it: let interval_id = null io.on('connection', function(socket) { if ...

dividing a matrix into sections (JAVA)

tag: I am working with an Array[n][n] where the size, n, is a power of two, and I am looking to recursively manage the quadrants of the array. Is there a way in Java to select a segment of the array that covers the elements from [0 to (size/2)][0 to (size ...

Not all words are compatible with word-wrap, don't you think?!

I have a situation where I used the following CSS properties for a div: word-wrap: break-word; text-align: justify; When a single word is too long to fit within the width of the div, it wraps or breaks into multiple lines. However, if a second word with ...

Exploring the inner workings of view encapsulation in Angular

It is common knowledge that the default view encapsulation for a component in an Angular application is Emulated. encapsulation: ViewEncapsulation.Emulated I am quite perplexed about how it functions without being a shadow DOM. ...

Conceal the top row of the second HTML table that does not contain any class or ID attributes

I have a scenario where I am working with two HTML tables within an iframe tag. These tables do not have any class or id attributes specified. My goal is to use jQuery to locate the first row of the second table and hide it. The structure of my tables is a ...

Retrieve information from an external JSON API using jQuery

I need help with reading JSON data using jQuery. I have tried the code below but it doesn't seem to be working. This is the link to my JSON file: and here is my code snippet: $.getJSON("http://goo.gl/PCy2th", function(data){ $.each(data.PlayList ...

Challenges when using NodeJs require('../file.js')

Currently, I am in the process of developing a nodeJs application using express, sequelize, and sqlite. Within my root directory, there is a dedicated routers directory where I keep all the '.js' files for express's routers. Additionally, in ...

Ensure that video controls remain visible for 3 seconds after hovering over them

Is there a way to make video controls only appear when hovering over the video and then disappear after three seconds when the cursor is moved away? The current behavior works correctly when the video is at the beginning, but if I hover while it's pla ...

The X axis labels are missing on the Google column chart

Problem: All column charts are rendering correctly in Internet Explorer. However, Upon clicking the "View Build Performances" button, project names are displayed on the x-axis of the first three column charts only. The other column charts do not show pro ...

Each time I load the page, it displays differently depending on the browser. I'm struggling to understand the reason

Trying to figure out how to make the navigation bar close when a link is clicked and directed to a section instead of a new page. When on a large screen, I want the nav bar to remain open but automatically close when on a small screen (for example, when th ...

Tips for managing a session when adding a List of strings

((List<string>)Session["answera"]).Add(xle.InnerText); I am encountering an issue while trying to execute this operation, it keeps showing "Object reference not set to an instance of...." I prefer not to use List<string> ast = new List<s ...

What is causing the loss of context for 'this' in the latest Angular 1.5 components?

Encountering a strange issue with the new components. Previously, in version 1.4 directive, we had this block of code... (function () { 'use strict'; angular.module('app.board').directive('dcCb', dcClipboardCopy); funct ...

transforming hex string into decimal number and back again

In this unique version of the hexadecimal system, A, B .... F are replaced by U-Z. #include<stdio.h> int main() { // Your program logic goes here. This is a comment line for reference. //1.taking user input of string char hexaDec[1 ...

The issue I'm facing in Jest is the "SyntaxError: Unexpected token 'export'" even after configuring transformIgnorePatterns

When executing npm run test, which triggers the execution of jest, a test suite fails with the following error message: /home/anthony/nosync/development/openmeteo/enhydris-web-frontend/node_modules/vue-notifications/dist/vue-notifications.js:130 export def ...

I utilize a Bootstrap modal popup to showcase user alerts across various sections of my website. Each instance of the modal window is triggered from different locations and displays personalized content

<div class="modal" tabindex="-1" role="dialog" id="myModal" data-backdrop="static" data- keyboard="false"> <div class="modal-dialog" role="document"> <div c ...

Using conditional statements to render content based on a certain condition within a

One of my requirements is to dynamically render a React component in the following manner: parent.ts ... <Parent> <Child/> <Parent> ... child.ts ... return (someBoolean && <Component/>) ... While ...

Don't forget about managing cookies in JavaScript!

Currently, I am developing a left sidebar menu that expands and collapses upon clicking a button. I need to find a way to save the state of the menu, whether it is expanded or collapsed, so that when the page is refreshed, the same class will still be app ...

Using ngFor in Angular 2-5 without the need for a div container wrapping

Using ngFor in a div to display an object containing HTML from an array collection. However, I want the object with the HTML node (HTMLElement) to be displayed without being wrapped in a div as specified by the ngFor Directive. Below is my HTML code snipp ...

Encountered a 400 error when attempting to send a request to a RestController in Spring MVC

I keep getting a "bad request 400" error when sending a request with parameters to the controller. I have double-checked the syntax but can't find any mistakes. Can someone please review my code and see what's wrong? var url = contextPath+"/bill ...