Simplest method for showcasing NodeList of childNodes? (Novice level)

Currently, I am exploring the DOM tree to retrieve HTML comments and showcase them in an alert box. However, I seem to be stuck as my alert box is always empty. Can someone guide me on how to properly display a nodeList array? I have spent hours searching for a solution but nothing seems to make sense.

<!DOCTYPE html>
<html>
<head>
    <title>Hidden Comments</title>
    <h1 style="text-align:center">Hidden Comments</h1>
    <script>
        function concatComs(){
            var c=document.getElementById('body');
            var array=[];
            for(var i=0;c.childNodes.length<i;i++){
                if(c.childNodes[i].nodeType==8) array[i]=c[i];   
            }
            alert(array.toString());
        }
    </script>
</head>
<body id="body" style="text-align: center">
    <!--you-->
    <h2>Find the hidden comments!</h2>
    <p>Look closely and you'll find them!</p><!--found-->
    <input type="button" value="Go!" onClick="concatComs()"/> 
    <!--them-->
</body>
</html>

Answer №1

To enhance your for loop, initiate it as follows:

for(var i=0; i < c.childNodes.length; i++){

Moreover, consider including c.childNodes[i] in your array.

function combineComments(){
    var c = document.getElementById('body');
    var array=[];
    for(var i=0; i < c.childNodes.length; i++){
        if(c.childNodes[i].nodeType==8) {
            array.push(c.childNodes[i]);
        }
    }
    var result = "";
    for(i in array) {
        result += array[i].textContent + " ";
    }
    document.write(result);
}
<div id="body" style="text-align: center">
    <!--you-->
    <h2>Uncover the hidden comments!</h2>
    <p>Observe closely to find them!</p><!--found-->
    <input type="button" value="Go!" onClick="combineComments()"/> 
    <!--them-->
</div>

Answer №2

If you want to extract comment strings using a regex expression, you can use the following:

match(/<!--.*?-->/g)

You can then remove the first 4 and last 3 characters from each string with this code:

substr(4,comments[i].length-7)

The final result will look like this:

<!DOCTYPE html>
<html>
<head>
    <title>Hidden Comments</title>    
    <script>
        function concatComs(){            
            var comments = document.body.innerHTML.match(/<!--.*?-->/g);

            for (var i = 0; i < comments.length; i++) 
                comments[i] = comments[i].substr(4,comments[i].length-7);

            alert(comments);
        }
    </script>
</head>
<body id="body" style="text-align: center">
    <h1 style="text-align:center">Hidden Comments</h1>
    <!--you-->
    <h2>Find the hidden comments!</h2>
    <p>Look closely and you'll find them!</p><!--found-->
    <input type="button" value="Go!" onClick="concatComs()"/> 
    <!--them-->
</body>

</html>

By the way, remember to place your h1 tag inside the body tag instead of the head tag.

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

The Mystery of Socket.io Random Disconnects (version 1.0.6)

Currently, I am utilizing the most recent version of socket.io (1.0.6) to develop an online multiplayer game using Phaser and Node. One issue that has arisen is that after the clients connect, they will sporadically disconnect without any specific pattern. ...

When iterating through HTML Elements using the forEach method, the getElementsByClassName function is not capable of targeting these specific elements

Allow me to elaborate, although you will grasp the concept better once you see the actual code. I am retrieving my div elements using the getElementsByClassName function and then converting them into an array using Array.from(). As I iterate through this a ...

The navigation bar in React Router is interfering with the loading of other components

Currently, I am in the process of setting up a simple navigation bar that consists of basic buttons without any complex functionality. However, I have encountered an issue where placing the navbar inside the switch prevents other components from loading ...

Fixing the "Parsing error: Parenthesized pattern" issue using vanilla JavaScript

I'm currently working on a project for a job training program using HTML and JavaScript. The online code editor allows me to execute my code and there is even an "evaluate" button that verifies it against different test cases. My code functions as exp ...

The de-duplication feature in webpack is not functioning properly when the splitChunks cacheGroups commons option is activated

In my lerna project, I have two identical packages named p1 and p2. Both p1 and p2 utilize a 3rd party package - in this case, eosjs@beta, which is approximately 50KB in size. When I incorporate p1 into an example react project, the package size increase ...

Exploring multidimensional JSON arrays with the jQuery each() method

What am I missing here? The first iteration works fine, but it breaks in the second one.. var testJSON = {"cluster":[{"node":[{"name":"one", "number":'100', "error":"none"},{"name":"two", "number":'200', "error":"none"},{"name":"three ...

Issue encountered with the URL for the image in a JSON file following the utilization of multer for image uploads in a Node.js

Using multer to upload images for a blog website. After uploading an image with Postman, the filename is saved in the data.json file under "uploads\" directory. How can I save it as "uploads/" instead of "uploads\"? data.json { "id& ...

Executing HTML code upon reaching the index.php page

I am facing an issue with running a specific code on my website. Here is the code I need to run: <font size='3'><b> <li class="icon-home"> <a href="{U_INDEX}" accesskey="h">{L_INDEX}</a> <!-- BEGIN na ...

Conceal flexbox item depending on neighboring element dimensions or content

I've encountered an issue while using a flexbox to display two elements side by side. The left element contains text, while the right one holds a number. When the value in the right element has at least 7 digits ( > 999,999 or < -999,999), I ne ...

Utilizing Angular 2+ with the [innerHTML] property to incorporate HTML with added style attributes

I am currently utilizing Angular 2+ [innerHTML] input for inserting HTML formatting that includes style tags. Within my template, the code looks like this: <span [innerHTML]="someVar"></span> In the component file, I have defined: someVar = ...

React-Troubleshooting list items and keys: A comprehensive guide to resolving common issues

I'm facing a challenge with generating unique key ID's for my list items. Even though I thought I had a good understanding of how unique keys function, it seems that I am mistaken. In the code snippet below, using key={index} or key={item} is no ...

Triple the number of arrays stored in MongoDB

How do you modify hour[2][5] in the array 'hours', specifically updating the second element of the array and then the fifth element of that second array by using the Document code? This example uses the Java driver for Mongo 3+. Document perso ...

What is the best way to store a personalized configuration for a user within a Node module?

For my CLI project in Node.js utilizing commander.js, I am interested in implementing a way to store user-specific configuration settings. This will allow users to input their preferences only once during the initial usage. What would be the best approac ...

sending data with JavaScript and AJAX to a PHP file

$(document).ready(function() { $(":input").focusout(function () { var a= $(this).closest("tr").attr('id'); var b= $(this).closest("td").attr('id'); var data = $(this).attr("value"); $.post("database.php", {trAdress: ...

Prevent the event from spreading down to the child elements

I believed I had a solid understanding of the concept of event bubbling, but now I am starting to doubt my grasp on it. I designed a semi-modal dialog like so: <div class="context-menu"> <div class="menu"> … </div> < ...

PHP - Retrieve a portion of an array

I am working with an array of key values that is structured as follows: array(5) { ["2014-04-24"]=> int(5) ["2014-04-25"]=> int(2) ["2014-04-27"]=> int(1) ["2014-04-29"]=> int(7) ["2014-05-2"]=> int(7) } If I want to us ...

Overlap of Interval Lists

Two sets of sorted and non-overlapping closed intervals are provided. Determine the intersection of these two sets of intervals. (In mathematical terms, a closed interval [a, b] (where a <= b) represents a range of real numbers x where a is less than ...

Why doesn't Mongoose automatically generate an _id for my array elements when I push them in?

I am looking for a way to have mongoose automatically add an _id field to the objects I push into my array. Here is my mongoose schema: var playerModel = new Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "Users", }, cl ...

Exploring the bounds of self-invocation functions in JavaScript

Have you ever wondered why self-invocation functions inside another function in JavaScript don't inherit the scope of the outer function? var prop = "global"; var hash = { prop: "hash prop", foo: function(){ console.log(this.prop); ...

Stop the primary router-view from being altered

Within my Vue application, I have a main component that contains the following router views: <router-view></router-view> <div class="modal"> <router-view name="modal"></router-view> </div> In vario ...