The specified class name cannot be found or is undefined after the function has

Here is a function that I have:

  var save = document.getElementById('savethis'+this.parentNode.childNodes[1].id);
    save.addEventListener('click', savethis.bind(this), false);

function savethis() {
  this.removeEventListener('click', edit);
  var a = this.childNodes[0].childNodes[0].id;
  console.log(a);
  var b = document.getElementById(a);
  console.log(document.getElementById(a).id.replace('minedit',''));
  console.log(b.value);
  this.innerHTML = b.value;
  this.parentNode.cells[4].className = 'text-center min-edit';


  setTimeout(function() {this.addEventListener('click',edit);},1);
}

Now, in another function:

var minedit = document.getElementsByClassName('min-edit');
 for (var m=0;m<minedit.length;m++){
    minedit[m].addEventListener('click', edit);
 }

function edit(){

    var avalue = this.innerHTML;
console.log(avalue);
    if (this.className.indexOf('input-open')>=0){

}

else {
    this.className += ' input-open';
    var content = '';
    content += '<div class="input-group editable-input"><input type="text" id="minedit'+this.parentNode.childNodes[1].id+'" value="'+parseFloat(avalue).toFixed(2)+'" class="form-control"><span class="input-group-addon editable-input" id="savethis'+this.parentNode.childNodes[1].id+'"><i class="ion-android-done" ></i></span><span class="input-group-addon editable-input"><i class="ion-android-close" id="close"></i></span></span></div>';
    this.innerHTML = content;


    valuenow = document.getElementById('minedit'+this.parentNode.childNodes[1].id).value;
    id = document.getElementById('minedit'+this.parentNode.childNodes[1].id).id;
 var save = document.getElementById('savethis'+this.parentNode.childNodes[1].id);
    save.addEventListener('click', savethis.bind(this), false);


}

}
function savethis() {
  this.removeEventListener('click', edit);
    var a = this.childNodes[0].childNodes[0].id;
    var b = document.getElementById(a);
    this.innerHTML = b.value;
    this.parentNode.cells[4].className = 'text-center min-edit';
    setTimeout(function() {this.addEventListener('click',edit);},1);
}

When you check the fiddle, you can see that the input box opens and closes on the first click but throws an error on the second click.

TypeError: this.className is undefined

This error stems from this line in the code:

 if (this.className.indexOf('input-open')>=0){

I am confused as to why className would be undefined, especially since I define its name within the savethis function. Can someone help clarify and provide a solution?

Answer №1

Issue: Incorrect Scope

setTimeout(function() {this.addEventListener('click',edit);},1);  

The reference to this is pointing to the document instead of the element.

var that = this;
setTimeout(function() {that.addEventListener('click',edit);},1);

An alternative solution is using bind() for modern browsers

setTimeout( (function() {this.addEventListener('click',edit);}).bind(this),1);

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

Using Postman Express, send raw JSON data via a POST request

I'm looking to capture and log all the data, then return it as a response. app.post('/data', (req, res) => { const data = req.body console.log(data) return res.json({ data }) }) Using Postman, I am sending data. In the Body ...

Trouble with displaying a cube from Blender to Three.js

Hey everyone, I'm having some trouble exporting a cube from Blender to three.js. I've exported the JSON file, but when I try to display the cube in my code, it's not showing up - instead, all I see is the setColor screen and I can't fig ...

Showing a gallery of images in React

I have a unique situation where I am working on setting a variable to match the import statement that calls for images. Once I have this variable assigned, I want to use it to display the corresponding image. For instance, if my code generates the name &ap ...

Issue with Iconify icon not updating when "data-icon" is set using setAttribute()

I'm having trouble trying to animate or replace an icon using the "setAttribute" method. Can someone take a look at my code and help me figure out what's wrong? <!DOCTYPE html> <html> <script src="https://code.iconify.design/1/1 ...

Best method for retrieving information from a string

Exploring different techniques to extract data from a string is a common practice, including methods like substring and split. Is there an optimal approach to accomplish this task? For instance, when faced with a URL structure such as http://myServer:8000/ ...

Challenges regarding placement and z-index are causing issues

Currently, I am attempting to make the menu overlap the content on my webpage. However, I am facing an issue where it moves the content box instead of overlapping it. I have already experimented with the position: relative concept, but unfortunately, the ...

<JavaScript> changing the color of hyperlink in d3.js - <Organizational Chart>

screenshot The width of the link can be adjusted, but the color remains unchanged. I have attempted various solutions series.links.template.setAll({ strokeWidth: 2, strokeOpacity: 0.5, color: am5.color('#ffffff'), links: ...

Tips for managing modal closure when the InertiaJS form succeeds?

Hello everyone! Currently, I'm involved in a Laravel project where I am using laravel/breeze VueJS with Inertia. The login functionality is implemented using a bootstrap modal component. While validation and authentication are working smoothly, the on ...

calling the setState function multiple times

I keep calling the setState function multiple times in a row by pressing the down button, but I noticed that React JS stops updating the state after around 40-50 updates. Each click increases the sold value by one. Is this normal behavior for React JS, or ...

Is there a intentional way to cause my node.js server to crash?

Is there a way to intentionally crash my node.js server? I want to trigger this action when specific fatal errors occur in order to immediately bring them to my attention for fixing. I came across a post about this topic here, but I am not interested in u ...

Choose particular content enclosed by two strings (across multiple lines)

Looking to use regex to extract specific text between two strings. For example: foo I have four toys bar //single line foo //multiline I have four toys bar foo I have three pets bar foo I have three pets bar How can I extract the text between & ...

Splitting a JavaScript string into a two-dimensional array

Can someone assist me with splitting a string into a two-dimensional array? This is an example of my input array: var str = 'a) first sentence without fixed length b) second phrase c) bla bla bla' The desired output array should look like this ...

Flipping and expanding cards with CSS3

I am attempting to create a layout with a collection of cards/divs within a container. When a card/div is clicked, it should flip horizontally and expand to occupy the entire space within the container (essentially resizing to 100% x 100% when clicked). I ...

Invoke a directive's function on a page by utilizing ng-click in AngularJS

Is there a way to call a function from a directive in an HTML page like index using ng-click? Below is the code for my directive: $scope.moreText = function() { $(".showMore").append(lastPart); }; html: <a ng ...

How can I retrieve the value of a div nested within another div?

Alright, let's talk about a situation where we have a draggable HTML div element: <div id="server" draggable="true" ondragstart="return dragStart(event)">Server</div> and also a target div: <div id="target1" ondragenter="return dragE ...

Using AJAX in Laravel Blade to bypass the specified div class

As a beginner in AJAX JavaScript, I have been trying to filter data in Laravel 10 without refreshing the page using AJAX, but so far I haven't had much success. Below is the code snippet from my blade view: <script src="https://code.jquery.co ...

What is the most efficient way to utilize a single connection to interact with MongoDB?

I have a series of functions that are responsible for running various queries. Here is the code I am working with: var MongoClient = require('mongodb').MongoClient; async function createDatabase() { MongoClient.connect(urlMongoDB, function(er ...

Updating state with new data in React: A step-by-step guide

Recently, I delved into the world of reactjs and embarked on a journey to fetch data from an API: constructor(){ super(); this.state = {data: false} this.nextProps ={}; axios.get('https://jsonplaceholder.typicode.com/posts') ...

Guide on invoking a distinct function for dynamically generated checkboxes within a specific div

In my project, I am attempting to dynamically generate a group of check-boxes that trigger different functions when clicked. function initializeButtons(variable, length) { for(c = 0; c < length; c++) { clicks.push(true); } for(i = 0 ...

When a div is created outside of the viewport, the overflow scroll feature will fail to function properly

I am currently working on developing a full screen slider with a unique feature on the last slide: a horizontal scrolling area. To achieve a smooth animation, I am using CSS translations to bring the div within the viewport. Oddly enough, the scrollbar do ...