Navigating an HTMLCollection with Javascript: A Guide

Currently, my code looks like this:

var links = document.getElementsByTagName('a');

It's meant to collect all the links on the page, but we need to make some changes.

When I use console log to check links, I see an HTMLCollection with over 100 'a' elements. However, links.length returns 0.

I've attempted various methods to convert this HTMLCollection to an array, but none of them seem to be effective.

Array.from(links)

Array.prototype.slice.call(links)

[].forEach.call(links, function (el) {...});

HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];

HTMLCollection.prototype.forEach = Array.prototype.forEach;

Every one of these attempts results in an empty array.

Furthermore,

var links = document.querySelectorAll('a');
also gives me an empty NodeList.

I've reached a dead end. The original links variable definitely contains elements, so it's perplexing why none of these approaches are successful. In addition, utilizing jQuery is not an option for our project.

Answer №1

Utilize the Array.from(HTML_COLLECTION) method to iterate through each element using a forEach loop and log each element to the console.

Answer №2

this method is effective for me

const allLinks = document.querySelectorAll('a');
const linkArray = Array.from(allLinks);

Answer №3

Another option is to implement an EventListener

window.addEventListener('load', function () {
  var links = document.getElementsByTagName('a');
  console.log(links);
}

Try this out

Answer №4

Just missed it:

let linksArray = Array.from(links)

Alternatively, you can create a helper function to handle node lists without always converting them to arrays. Here's an example:

function forEachElement(elements, callback){
  elements.forEach(element => {
    callback(element);
  });
}

forEachElement(links, function(link){ console.log(link); })

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 correct way to create an if statement that checks if a style attribute is empty?

Currently, I am working on a feature that involves toggling the struck-through style of a span element when clicked. After experimenting with an if statement to determine the textDecoration attribute's value using console.dir(x), I found that the retu ...

I encountered no response when attempting to trigger an alert using jQuery within the CodeIgniter framework

Jquery/Javascript seem to be causing issues in codeigniter. Here is what I have done so far: In my config.php file, I made the following additions: $config['javascript_location'] = 'libraries/javascript/jquery.js'; $config['javas ...

I possess a webpage containing a div element that is loaded dynamically through ajax

One issue I'm facing is with a page containing a div that gets loaded via ajax when a button is clicked. The problem arises when a user tries to refresh the page by pressing F5, as the content of the div gets lost! Is there a way to ensure that when ...

What is the best method for serving cross-site content - JSONP, iframe, or a different approach?

In the process of developing an ad network, I am faced with the task of integrating third-party websites to include my JavaScript and replace specific divs with my content. Choosing which content to serve dynamically into these divs necessitates a cross-s ...

Using Accordions in Jquery to dynamically adjust page height during ajax calls

I am currently using AJAX to call in a page and animate its height successfully. However, I have encountered an issue with an accordion-like function that is supposed to toggle the visibility of an element and adjust the height of the containing element ac ...

Why is my Feed2JS RSS feed functional locally but not operational after deployment on GitHub Pages?

I've been using feedtojs.org to display my Medium blog posts on my GitHub Pages website. Strangely enough, it works perfectly fine on my local server but not on the actual domain. The RSS feed is valid. Here's how it appears on my local server: ...

Looking for a way to add a permanent footer to the bottom of your webpage without affecting the tab order for accessibility?

I have a paginated form with a fixed navigation footer at the bottom that needs to stay in place even when scrolling. This footer should also be at the bottom of the page for mobile devices and tablets. To achieve this, I used position: fixed on the foote ...

Determine the quantity of items that meet specific criteria

The initial state of my store is set as follows: let initialState = { items: [], itemsCount: 0, completedCount: 0 }; Whenever I dispatch an action with the type ADD_ITEM, a new item gets added to the items array while also incrementing the count in ...

include the ReactToastify.css file in your project using the import statement

Error in file path C:\Users\User\Documents\GitHub\zampliasurveys_frontend\node_modules\react-toastify\dist\ReactToastify.css:1 ({"Object.":function(module,exports,require,__dirname,__filename,jest){:ro ...

NextJs not processing Bootstrap form submissions

I’m struggling to figure out why my form isn’t submitting when I click the submit button. The backend seems fine because Postman successfully sends the information to the database. However, nothing happens when I try to submit the form. My tech stack ...

Receiving an error of "undefined" when trying to capture the selected

One issue I am facing is capturing the selected user option and sending that value in a post request. Let's put aside the post part since it's not directly related to the main question at hand. Currently, the value is showing up as undefined. ...

Combining file and JSON data in React and Express: A guide to uploading both simultaneously

I am looking to send both a file and JSON data from a form using my react handle submission method. const formData = new FormData(); formData.append('File', selectedFile); const data = { name: 'vasu', email: 'example@example ...

Utilize AngularJS to Capitalize the First Letter and the Letter Following a Dot (.)

I am seeking a solution to capitalize the first letter in a given string, like so: sumo => Sumo Additionally, I need to capitalize strings in the following format: Dr.ravi kumar => Dr.Ravi kumar Although I have implemented an Angular filter that ...

Customize your popover content with Bootstrap settings

I've been on a quest to dynamically update the content of a Bootstrap popover using JavaScript, but unfortunately, the methods I've tried so far haven't worked out as expected : <!--object with the popover--> <input id="popoverlist ...

Converting HTML to CSV using PHP

I need assistance with exporting MySQL fields to CSV. I have successfully exported all fields except the one that contains HTML content. My MySQL table is structured as follows: Name: Address: Profile: The 'Name' and 'Address' fields ...

What is the best way to utilize Google Maps autocomplete while filtering addresses by county and city?

Currently, I am working on a project that requires integration of the Google Maps autocomplete address API. In the registration form, I need to collect the user's address in three separate input fields: Country: ______________ City: _______________ ...

Angular connecting to the count of filtered items

Here's the array I'm working with: [ { type: "hhh", items: [ { "name": "EGFR", "type": "a", "selected": true } ] }, { type: "aaa", items: [ { ...

Customizing the placeholder font size in Material UI Autocomplete using ReactJS

Is there a way to change the placeholder font size for Material UI Autocomplete? https://i.stack.imgur.com/x71k2.png <Autocomplete multiple id="tags-outlined" options={top100F ...

Having trouble deleting element despite having the correct ID?

Whenever I click on the map, it adds an element to the map div using this line of code: $('#map').append('<label>test:</label><input type="hidden" name="map_coords" id="' + e.latlng.lat + '" value="' + e.latlng ...

What is the most efficient way to calculate the total sum of elements in

When running this code, I am getting a result of "0": Map<Integer, Long> bwvm=BwProvisionerSimple.getBwConsumed(); Map<Integer, Long> map = new HashMap<Integer, Long>(); long sum = 0; for (Long val : map.valu ...