Utilizing `getElementById( x )` to assign `someFunction` to an onclick

I pondered for quite some time on how to articulate the issue, but I couldn't. I need assistance in elucidating the code.

My goal is to create a basic JavaScript organizer. The user inputs a task and clicks on the "add to the list" button, which generates a checkbox with a paragraph containing the task text. Additionally, I want the ability to disable the checkbox and strike through the task text when clicked on. I attempted to achieve this by assigning a function (destroyIt()) to each checkbox I create that would disable it upon clicking, but it only seems to work for the last checkbox added. I've been examining this code extensively, but I can't pinpoint what's wrong. Any help would be appreciated. Here is my code:

<html>
<head>

    <style id="stil">
        .over{
            text-decoration:line-through;
        }
    </style>


    <script type="text/javascript">
        var numberOfTasks=1;

        function insertNew(){
            tekst = document.getElementById("zadatak").value;
            if(tekst.length>0){
                var idEl= "check"+numberOfTasks;

                document.getElementById("ispis").innerHTML+="<input type='checkbox' id='check"+numberOfTasks+"'> "+"<span class='"+idEl+"'>"+tekst+"</span> <br/>";

                document.getElementById(idEl).onclick= function(){ destroyIt(idEl); };

                numberOfTasks++;
            }
        }       
        function destroyIt(idEl){
            document.getElementById(idEl).disabled=true;
            document.getElementById("stil").innerHTML+= "."+idEl+"{text-decoration:line-through;}";
            alert(idEl+"{text-decoration:line-through;}");
        }


    </script>
</head>

<body>
    Tasks for: <span id="date"> </span>

    <script>
        var date= new Date();
        document.getElementById("date").innerHTML= ""+ date.getDay() +"." +date.getMonth() +"." +date.getFullYear();
    </script>

    <br/> <br/>
    New task: <input type="text" id="zadatak"> <button onclick="insertNew()"> add to the list </button>

    <button onclick="provera()">Provera</button>
    <p id="ispis"> </p>
</body>

Answer №1

One issue arises when using .innerHTML += "...", as it replaces existing nodes and their event handlers with new ones. It's recommended to avoid using += after .innerHTML.

A better alternative for inserting HTML content is to utilize .insertAdjacentHTML(). This method takes two arguments: the position relative to the element and the new content to be inserted.

Incorporating .insertAdjacentHTML() into your code would appear like this:

function insertNew(){
    tekst = document.getElementById("zadatak").value;
    if(tekst.length>0){
        var idEl= "check"+numberOfTasks;

        document.getElementById("ispis")
                .insertAdjacentHTML("beforeEnd", "<input type='checkbox' id='check"+numberOfTasks+"'> "+"<span class='"+idEl+"'>"+tekst+"</span> <br/>");

        document.getElementById(idEl).onclick= function(){ destroyIt(idEl); };

        numberOfTasks++;
    }
}       

Moreover, you can enhance the destroyIt function by operating on its this value, which allows access to the input element having the handler. From there, you can extract the class of the span or navigate to the next element.

Avoid altering the style sheet to hide an element; simply add a class or use a direct style property.

In the previous function, instead of:

document.getElementById(idEl).onclick= function(){ destroyIt(idEl); };

You should use:

document.getElementById(idEl).onclick= destroyIt;

The revised destroyIt function becomes:

function destroyIt(){
    var span = this.nextElementSibling;
    this.disabled=true;
    span.style.textDecoration = "line-through";
}

Note that .nextElementSibling requires patching in IE8, although this example serves as a basic demonstration.

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

When the dialog is opened, automatically set the focus on the text field inside

I am facing an issue with focusing a custom text field when opening a dialog. I have tried using vue.js refs: Code: <v-app id="app"> <v-row align="center"> <v-col class="text-center" cols="12"> <v-btn color="primary" @cli ...

Tips for utilizing an IF statement in a Protractorjs Spec.js document?

I am attempting to execute the spec.js file across multiple browsers using Multicapabilities in conf.js. However, I specifically want a certain line of code to only run for Internet Explorer. I have tried putting this code snippet inside an IF statement w ...

Is it possible to duplicate a div element and then make changes to both the original and the clone using a single button

I am dealing with an element that has three sub-elements element1, element2, and element3. When I press the button1 command, it filters element1. When I press the button2 command, it filters element2. How can I clone this element and manipulate both th ...

A step-by-step guide on creating a backbone.js view function that automatically scrolls a specified DOM element with CSS overflow

Is there a way to write a backbone.js view method that automatically scrolls down a DOM element with CSS overflow? Let's assume we have created an overflow div with the id "overflowdiv" <div id="overflowdiv"></div> This div is filled fr ...

Looking for the Tree in the backend 3D model of Three.js

Lately, I've been exploring various WebGL showcases and came across three.js, a widely popular framework that even has its own dedicated book by Toni Parsli. Upon examining the source code of three.js, I was surprised not to find any traditional scene ...

Instructions on removing rows by using buttons within a JavaScript-generated table

This snippet displays JS code to create a quiz index table and HTML code to display the index. function load(){ var data = [ { "id": "qc1111", "quizName": "Quiz1", "course": "111", "dueDate": "1/ ...

Using THREE.js: Finding the nearest point between two rays in a THREE.js environment

In my current project with THREE.js, I am working with two THREE.Ray objects. Both rays have an origin point represented by a Vector3 and a direction indicated by another Vector3. I am currently exploring how to determine the nearest intersection point be ...

Guide on updating location and reloading page in AngularJS

I have a special function: $scope.insert = function(){ var info = { 'username' : $scope.username, 'password' : $scope.password, 'full_name' : $scope.full_name } $http({ method: &ap ...

The useMutation function trapped in an endless loop

I've been encountering an issue while running a query to save an entity in the database using usemutation. The saveVisa() mutation seems to be stuck in an infinite loop, creating the same element multiple times without any clear reason. import {React, ...

"CSS background not loading properly on jQuery infinite scroll feature, affecting the loading of

Currently, I am using the most recent version of infinite-scroll developed by paulirish. Everything seems to be working correctly, but there is a peculiar issue that I have encountered. Consider this scenario: You have a forum where infinite scroll is imp ...

What is the best way to transform this JSON data into an array of key-value pairs in JavaScript?

Dealing with nested JSON data can be challenging, especially when trying to extract key-value pairs efficiently. If anyone has suggestions on how to simplify this process and improve readability, please share your insights. The goal is to transform the ne ...

Execute a function on elements that are added dynamically

I'm in the early stages of learning javascript and jquery, so this issue might be very basic. Please bear with me. Currently, I am dynamically adding new link (a) elements to a division with the id "whatever" using the following code: $("#whatever") ...

Changing the border of an iframe element using jQuery or Javascript from within the iframe itself

Is it possible to set the border of an iframe to zero from within the iframe itself using JavaScript or jQuery? Any guidance on how this can be achieved would be greatly appreciated. Thank you! ...

Step-by-step guide on building a factory in Angular for a pre-existing service

Currently, I am delving into the world of angularjs and exploring articles on service and factory functionalities. One particular example that caught my attention is showcased in this ARTICLE, which includes a demonstration using a Service Fiddle. As I de ...

Issue with history.go(-1) method malfunctioning on dropdown menu

Currently, I am facing an issue with the functionality of my back button using history.go(-1) in conjunction with a dropdown selection. Despite the source code displaying the original selected value, the UI is showing a previous value. When clicking on t ...

"Creating a unique Three.js cube by applying different textures on each face. Learn how to conceal edges and vertices for

I'm currently working on a project using Three.js where I want to create a Cube with unique images as textures on each face. Is there a way for me to conceal the edges and vertices of the mesh? Here's the code snippet: var container, camera, s ...

How can I place an icon on a specific location in a Highcharts map?

I am currently utilizing Highcharts to showcase maps within my application. I am aiming to achieve two specific functionalities: 1) Upon clicking on any area, I want that area to be highlighted in red {completed} 2) Upon clicking on any area, I intend f ...

Discovering the precise date format within highcharts

I've been searching for a while now, but I still haven't found the perfect solution to this issue: The date highlighted in the red box in the image needs to adjust based on the user's country location. For example: For users in the US -> ...

Tips for setting up a cleanup function in useEffect when making API calls within a context provider

Looking to showcase a list of products categorized and fetched from an API? Check out the code snippet below: const API = "https://dummyjson.com/products"; const ProductsList = () => { const { cate } = useParams(); //retrieving category fro ...

I encountered an error message stating "Unexpected token {" while trying to import the module "express-fileupload"

Struggling to implement file uploading with NodeJS on Ubuntu, encountering errors. Upon adding const fileUpload = require('express-fileupload'); the app fails to compile, throwing this syntax error: 2|theproje | /home/asgeir/nodejs/first_test ...