What is the best way to target and select all spans within a specific div using JavaScript?

I'm struggling with selecting all spans in the card using code that currently only selects the first span when I use getElementsByTagName. Can anyone offer assistance as I have multiple cards containing spans?

TypeError: Failed to execute 'insertBefore' on 'Node': parameter 2 is not of type 'Node'. at HTMLDivElement.

Here is the JavaScript code snippet I am working on:

const last = document.getElementById('last');

last.addEventListener("click", (event)=>      
  {
  if(event.target.tagName === 'I')            
    {
    const icon = event.target;                       
    const card = icon.parentNode;
    if(icon.getAttribute('value') === 'remove')      
      {
      last.removeChild(card);                        
      }
    else if(icon.getAttribute('value') === 'edit')   
      {
      const span      = card.firstElementChild;
      const input     = document.createElement('input');  
      input.type      = 'text';                           
      input.value     = span.textContent;                 
      card.insertBefore(input, span);                     
      card.removeChild(span);                             
      icon.className  = 'fa fa-check-circle';             
      icon.setAttribute('id','green-color');              
      icon.setAttribute('value','');                      
      }
    else if(icon.getAttribute('value') === '')
      {
      const input      = card.firstElementChild;
      const span       = document.createElement('span');
      span.textContent = input.value;                    
      card.insertBefore(span, input);                    
      card.removeChild(input);                           
      icon.className   = 'fa fa-edit';                   
      icon.setAttribute('id','');                       
      icon.setAttribute('class','fa fa-edit edit');     
      icon.setAttribute('value','edit');                 
      }
    }
  })

<div class="row last" id="last">
  <h4 class="exam-header col-12">Schedule of exams dates</h4>
  <a class="exam-info teacher-link text-md-center col-8" id="teacher-link" href="#">
    <span class="subject subject-name">Computer Science</span>
    <span class="subject subject-date">2021/12/2</span>
    <span class="subject subject-time">9:00 AM</span>
    <span class="subject subject-duration">2h</span>
    <i class="fa fa-edit edit" value="edit"></i>
    <i class="fa fa-times remove" value="remove"></i>
  </a>
  <a class="exam-info teacher-link text-md-center col-8" id="teacher-link" href="#">
    <span class="subject subject-name">Computer Science</span>
    <span class="subject subject-date">2021/12/2</span>
    <span class="subject subject-time">9:00 AM</span>
    <span class="subject subject-duration">2h</span>
    <i class="fa fa-edit edit" value="edit"></i>
    <i class="fa fa-times remove" value="remove"></i>
  </a>
</div>

Answer №1

If you want to improve the way you listen to events on multiple divs or cards, here's a handy tip. Instead of attaching event listeners to each individual card, get a reference to the main element containing all the cards and listen for clicks on that element.

const cardContainer = document.querySelector('div.card-list');
cardContainer.addEventListener("click", (event) => {
  const clickedElement = event.target;
  // Add your event handling logic here - make sure to verify the 'target' is the right element.
});

Another useful technique is to use querySelectorAll to select multiple elements, then iterate over them using a loop:

const allSpans = document.querySelectorAll('div span');

allSpans.forEach((span) => {
    // Perform actions with each span element
})

Answer №2

  • For those interested in experimenting with getElementsByTagName or ClassName, here is a sample code snippet to help you get started:
var div = document.getElementsByTagName("div")[0]
var spans = div.getElementsByTagName("span");
for(let i = 0; i < spans.length; i++) {
  spans[i].innerText = 123;
}

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

Tips for extracting a value from a geojson response using a specific key

When analyzing the geojson response below, I am trying to access the following: Type and Segments To achieve this, I attempted the following: return data["type"] //does not work, error received return data["features"][0]["properties"]["segments"] ...

Error encountered when attempting to trigger a Bootstrap dropdown within a designated div

When using React JS, I encountered an issue when trying to trigger a dropdown that was nested inside a div with the class name "row". Initially, I placed the data-toggle and data-target attributes inside the div, like so: <div className="row"> < ...

"Encountering an unfamiliar authentication strategy while using NodeJS passport

I am currently developing a project using node.js with passport authentication. However, I am encountering the following error message: Error: "Unknown authentication strategy " Below is my code: LocalStrategy = require('passport-local').Strat ...

Rephrase the ajax call and the data retrieved

I'm struggling to find a solution for writing this code snippet without using async: false,. var imageX; var groupX; $.ajax({ type:'GET', url:'php/myphp.php', dataType:'json', async: false, success: ...

Comparing hardware-accelerated CSS3 animations, transitions, and jQuery animate for mobile devices

While developing my app using PhoneGap and jQuery, I encountered a dilemma regarding animations. Initially, I relied on what I knew best - jQuery animate - to create smooth movements. However, discussions about hardware acceleration caught my attention. ...

Error encountered when trying to generate a collection from JSON using Backbone framework

jQuery(function() { var Hotel = Backbone.Model.extend({ defaults: { idHotel:"", hotelName:"Grand Marina", hotelAddress:"Lakeview Drive", hotelStars:"4", hotelRoomsCount:"180", ...

The Flask web API is unable to process image files sent through AJAX requests

My Flask API is quite basic and it interacts with a DNN model. The Python backend code looks something like this: from flask import request from flask import jsonify from flask import Flask import io app = Flask(__name__) @app.route("/predict" ...

Display a table showcasing precise array data using Angular

In the app.component.ts file, I have created an array called "data" containing strings separated by commas. To format it in a way I desire, I parse it into JSON and use console.log to neatly display it as follows: const jsonData = Papa.parse(content, {ski ...

Executing a post request using axios

Having some trouble with a post request using axios and it's refusing to cooperate. Here is the specific request I need to make. This is what I attempted: await axios.post( 'https://api.searchads.apple.com/api/v4/campaigns/XXXX/adgroups/targ ...

Formatting a contact form to display information in an email

I'm interested in finding ways to customize the appearance of contact form results that are emailed to me. I want the information submitted through the contact form to be presented in a visually appealing manner when it reaches my inbox. Below is a s ...

Python code encountered an issue while trying to find the element with the locator //input[@name="session[username_or_email]". The element could not

I have recently started learning about selenium and web scraping in general, and today I attempted to follow a tutorial on selenium that included the following command: from selenium import webdriver driver = webdriver.Firefox() driver.get("https://t ...

When lines are added to a file in Node.js, the content is written in a haphazard sequence

I've encountered an issue with the code I wrote where the header line is not consistently at the top. It seems to randomly appear on the second or third line instead. I've tried troubleshooting multiple times without success, so any help would be ...

Simulated function for handling express functions

I'm currently working on a server.js file that includes an app.get function. To test this function using "jest", I am having trouble writing a mock function for the app.get implementation shown below. app.get('/api/getUser', (req, res) => ...

Is it possible to echo a CSS class using PHP?

I have a PHP structure and I would like to embed my div in PHP. I need to write CSS with echo class, but I am unsure of how to do it. Here is my div: <div class="mydiv"> <img src="catalog/view/theme/default/img/mypng.png" alt=""> </div ...

Determine whether the textfield is a number or not upon losing focus

I'm seeking advice on implementing a feature using jQuery and JavaScript. I want to create a text field that, when something is inputted, will automatically add .00 at the end if it's only a number. However, if someone inputs something like 2.00, ...

Tips for managing an event using the bxSlider callback API

I am currently using bxSlider to create a slideshow on my website. However, I now want to implement a manually controlled slideshow that also displays text content related to each image below the slideshow: Here is the code I have so far: <!--SlideSho ...

What are some reasons for the slow performance of AWS SQS?

My current project involves measuring the time it takes to send a message and receive it from an SQS queue. Surprisingly, the average time it takes is between 800-1200 ms, which seems like an excessively long period. Below is the code I have been using for ...

I am having trouble getting ng-change to work. Can someone explain how to properly implement ng

I am facing an issue where the ng-change function is not working for obtaining the team_id and team name. Can someone suggest a more efficient solution to resolve this problem? <th style="width:20%"> <select style="height: 40px; fon ...

Create a Three.js material that displays only the outline without any fill

Currently, I am attempting to create a visualization of a space time cube like the one shown at this link: using the webgl javascript framework known as three.js. One challenge I have encountered is trying to achieve the effect of having the cube displ ...

How to transform complex JSON into a nodes and links format using JavaScript with various key values

I am looking to transform my JSON array data into a structured tree format. The current JSON data is in the form: "data": { "name": "Sint Maarten", "introduction": {...}, "geography& ...