Do forEach methods allow the use of template literals in nested console.log functions?

I'm facing an issue with my forEach method in JavaScript. When I use template literals inside it, the console prints out [object HTMLLIElement] instead of the actual content of the

"<li class="sel">..."
element.

const container = document.querySelector("#start");
let sel = container.querySelectorAll(".sel");

//The following works correctly:
   // sel.forEach((element, pos) => console.log( element,pos));
//However, this does not
sel.forEach((element, pos) => console.log( ` ${element} + ${pos} `)); //and prints " [object HTMLLIElement] + 0 "
 <div id="start">
        <ul>
            <li class="sel">valoare 1</li>
            <li class="sel">valoare 2</li>
            <li class="sel">valoare 3</li>
            <li>valoare 4</li>
            <li class="sel">valoare 5</li>
        </ul>
    </div>

Answer №1

To extract the element's content, you can use outerHTML.

const container = document.querySelector("#start");
let sel = container.querySelectorAll(".sel");

sel.forEach((element, index) => console.log( `${element.outerHTML} + ${index} `));
 <div id="start">
        <ul>
            <li class="sel">value 1</li>
            <li class="sel">value 2</li>
            <li class="sel">value 3</li>
            <li>value 4</li>
            <li class="sel">value 5</li>
        </ul>
    </div>

Answer №2

Utilizing template literals enforces a .toString() call on the element reference, resulting in [object HTMLLIElement].

As stated in the documentation:

If toString() is not customized in an object, it returns ""[object type]"", where type represents the object type.

Omitting the template literal leaves the rendering of the value to the browser, which yields the raw HTML of the element by implicitly invoking element.valueOf().

const div = document.querySelector("div");
console.log(div);             // Implicit .valueOf() call
console.log(div.valueOf());   // Explicit .valueOf() call

const el = div;
console.log(`${div}`);        // Implicit .toString() call
console.log(div.toString());  // Explicit .toString() call
<div>test</div>

Therefore, when using template literals, bear in mind that you are requesting to output the string representation of the element itself rather than a specific property of the element.

In your scenario, template literals are unnecessary since the forEach arguments provide access to the required data via the element node interface, and calling element.outerHTML will yield the complete HTML of the element.

document.querySelectorAll("#start .sel").forEach(
  (element, pos) => {
    // The forEach element argument provides a reference to the
    // element instance being iterated. You can access anything
    // you need through that element's API:
    console.log(element.nodeName, 
                element.className, 
                element.textContent, 
                element.outerHTML,
                pos);
   }
);
<div id="start">
        <ul>
            <li class="sel">valoare 1</li>
            <li class="sel">valoare 2</li>
            <li class="sel">valoare 3</li>
            <li>valoare 4</li>
            <li class="sel">valoare 5</li>
        </ul>
    </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

What is the best way to combine a list of jsonNodes into a single jsonNode?

I've been working with the Jackson library in Java and I have a collection of objects that serve as wrappers for jsonNodes. I need to convert this list of jsonNodes into a single jsonNode. I attempted the following method: public JsonNode converte ...

Using jQuery to Iterate Through an AJAX Response

I'm working on a tagger application. When a user submits a tag, ajax sends the following response: {"returnmessage":"The Ajax operation was successful.","tagsinserted":"BLAH, BLOOOW","returncode":"0"} My goal is to extract the tags inserted and dyna ...

Differences between ng build --prod and ng --build aot in Angular 7

Recently, I successfully built an Angular 7 application using the command ng build --prod. However, I am now facing a dilemma regarding ng build --aot versus ng build --prod. Our application is currently deployed on ..., and although it runs successfully ...

Custom styling options for Google Chart

I have been attempting to dynamically adjust the width and height of a google-chart directive by utilizing input field values. However, I am encountering an issue where the width and height are not updating as expected. Check out the Plunker here $scope. ...

Tips for maximizing page layout efficiency without compromising on element visibility

What is occurring https://i.stack.imgur.com/Agjw6.gif The use of .hide() and .fadeIn(200) is resulting in a jittery effect that I would like to avoid. Desired Outcome When the user hovers over the menu icon, the menu icon should vanish the text "Pr ...

What steps can be taken to resolve the issue with Angular routing?

import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import {HomeComponent} from "./home/home.component"; import {SettingsComponent} from "./settings/settings.component"; ...

Using Angular to dynamically display JSON data on an HTML page

I have JSON data that I need to format into an HTML page where each parent becomes the header and its children are displayed under the same parent in the content area. Another parent will follow with its respective children listed below. How can I achiev ...

Create a Java array of LinkedList, utilizing the @SuppressWarnings("unchecked") annotation

i have checked previous answers regarding defining an array of linked lists in Java, such as How to properly define an array of linked list in Java ? and How do I fix "The expression of type List needs unchecked conversion...'? In my code, I h ...

Place 4 divs within 2 divs, with one aligned to the left and the other to the right

I'm currently working on a small project using Angular 2 for an experiment, where I need to place 4 divs, each containing an image, within 2 divs. However, all the divs (with images) are stacked vertically instead of being placed next to each other, ...

Can HTML5 be used to store IDs in PHP chat applications?

I'm in the process of developing a chat application with PHP. Everything is functioning properly, but I have encountered a potential loophole. I am implementing AJAX to fetch chat data as the user scrolls, similar to platforms like Facebook and Twitte ...

Focus on the iPad3 model specifically, excluding the iPad4

I am looking to apply specific CSS that works on iPad 3, but not on iPad 4, or vice versa. Currently, I am able to target both versions by using the following code: @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and ( m ...

What is the best way to access the inner html of every cell within a table row that I have selected?

I want to implement a feature on my website where users can click a "save" button on a specific row in a table and save the entire row's innerHtml onto another page as their favorite hiking trails. I've been trying to achieve this by adding clic ...

Shiny silver finish using three.js technology

I have recently started exploring three.js and am attempting to replicate a cube that looks like this: https://i.sstatic.net/CO9Eq.jpg One aspect I'm struggling with is creating the material for my cube. The material appears to be a silver polished fi ...

Issues with $routeProvider in a web page hosted by Express.js

As I embark on creating my very first Express.js/Angular application, I'm encountering a challenge with the $routeProvider in the page served by the Express.js application. Let's take a look at the server.js: var express = require('express& ...

React component's object value is set to undefined upon clicking a button

Encountering a strange issue where the object values (strings) disappear when switching between components on button click. The values are passed as props from a single object and display fine initially, but become undefined after transitioning to another ...

What is the best approach to creating a versatile JavaScript module that can be easily customized for various scenarios?

I am in the process of developing a JavaScript module that will submit data via an AJAX request when a button (next or previous) is clicked at the bottom of a modal. Once the data is submitted, the next modal out of a total of 4 will be displayed. The cha ...

Using Laravel and AJAX to save multiple selected filters for future use

I've been struggling with this issue for a few weeks now and just can't seem to wrap my head around it. On my webpage, I've implemented four filters: a search filter, a year filter, a launch-site filter, and a country filter. Each of these ...

Different kinds of functions can take an optional property name as an argument and either return the value of that property in an object or the entire object itself

In need of a function that accepts an optional parameter propName, which must be a key belonging to SOME_OBJECT. The function should return the value of propName if it is provided, or else return the entire OBJECT: Here's the code snippet: type SOME_ ...

What is the best way to enlarge text size with jquery?

I am attempting to: $('a[data-text="size-bigger"]').click(function () { a=$('span'); b=$('span').css('font-size'); a.css('font-size', b+1); } ); Initially, I ha ...

Executing functions asynchronously with callbacks using Node.js setTimeout

I have a node.js app running with a process that executes every 500 milliseconds. Occasionally, the process takes longer than 500ms to complete which causes issues when using setInterval. To address this, we modified our approach to use setTimeout with a ...