What is the best method for utilizing the jQuery Selector in this particular web application?

I have been attempting to figure out how to select a delete icon within my personal web application. delectIcon

HTML

<main>
    <div class="container">
        <div class="tabs">
            <a href=""><p><span class="active">Newest</span></p></a><a href=""><p>
            <span>Oldest</span></p></a><a href=""><p><span>Add</span></p></a>
        </div>
        <div class="content">
            <ul>
                <li>
                    <span class="itemLeft">Answer emails</span>
                    <span class="itemMiddle">12-31-2016</span>
                    <span class="itemRight">1</span>
                    <b class="deleteIcon"> X </b>
                </li>
                <li>
                    <span class="itemLeft">Prep for Monday's class</span>
                    <span class="itemMiddle">12-31-2016</span>
                    <span class="itemRight">5</span>
                    <b class="deleteIcon"> X </b>
                </li>
            </ul>

        </div>
    </div>
</main>

JavaScript

    $(".deleteIcon").on("click", function () {
    alert("Oh, clicked!");
    return false;
});

Despite my attempts to manually write the code, I wasn't successful in selecting the delete icon. Subsequently, I utilized Chrome Web Developer Tool to locate the CSS path. Experimenting with both XPath (

$"[/html/body/main/div/div[2]/ul/li[ 1 ]/b]"
) and CSS Path (
$"(pathbody > main > div > div.content > ul > li:nth-child(1) > b)"
) proved unsuccessful.

My efforts to apply an ID to mark only one "li" element as existent worked perfectly with the CSS selector. However, clicking on the deleteIcon ($"(#deleteIcon)") yielded no results.

#deleteIcon{

float:right;

font-weight: bold;
padding: 0 3px 0 3px;
border-radius: 5px;
background: #ccc;
cursor: pointer;
margin-left: 5px;
font-size: 1.3em;
text-align: center;

}

Another attempt was made to select the title. It was found that the following code snippet functioned properly:

  $(".container h1").on("click", function () {
    alert("Oh, no!");
    return false;
});

I am now uncertain about what steps to take next. Any assistance would be greatly appreciated!

Thank you! I warmly welcome any insights or solutions you may provide regarding my query.

Adding more details:

As a matter of fact, I added the deleteIcon into the HTML through JavaScript. I wonder if this action has affected my selector.

Actual HTML

<main>
    <div class="container">
        <div class="tabs">
            <a href=""><p><span class="active">Newest</span></p></a><a href=""><p>
            <span>Oldest</span></p></a><a href=""><p><span>Add</span></p></a>
        </div>
        <div class="content">



        </div>
    </div>
</main>

JavaScript (The important part listed below)

function Item(name,dueDate,type){
    this.name=name;//1
    this.dueDate=dueDate;//input2
    this.type=type;//3
};




$(".tabs a span").toArray().forEach(function (element) {
    var $element = $(element);

    // create a click handler for this element
    $element.on("click", function () {
        var $content,
            $input,
            $button,
            i;



        if ($element.parent().parent().is(":nth-child(1)")) {
            // newest first, so we have to go through
            // the array backwards

            $content = $("<ul>");
            for (i = Task.length-1; i >= 1; i--) {
                // $buttondelete = $("<buttonDelete>").text("X");
                var txt1 = Task[i].toStringName();
                var txt2 = Task[i].toStringDate();
                var txt3 = Task[i].toStringType();
                //alert(txt3);
                $content.append('<li> <span class="itemLeft">'+txt1+'</span> <span class="itemMiddle">'+txt2+'</span> <span class="itemRight">'+txt3+'</span><b class="deleteIcon"> X </b>');

            }
        }



        $("main .content").append($content);

        return false;
    });
});

Answer №1

In the case of dynamically generating items within a ul element, it is important to correctly bind the click event as shown below:

$(".content").on("click", ".deleteIcon", function()
{
alert("You have clicked on the delete icon");
return false;
} 
) ;

Answer №2

Using a period followed by the class name is how you target elements with that specific class (similar to your functioning example).

Give this a shot

$(".deleteIcon").on("click", function () {
    alert("Clicked!");
    return false;
});

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 best way to retrieve a specific key from a JavaScript Map containing an array?

I am currently iterating through a two-dimensional array to populate a map. The map is using the [i,j] indices as keys and the corresponding arr[i][j] values as values: const arrMap = new Map() for(let i = 0; i < arr.length; i++){ for(let j = 0 ...

What are some ways to disguise websockets?

I'm currently working on writing a JavaScript client that sends websockets to a node.js/ws server. I've been doing a lot of research and have come across information indicating it's useful, or even required by RFC, to mask all data sent from ...

The Javascript/Jquery code executes just once on the initial event, doubles on the subsequent event, and continues to increase in

There is a JS function attached to an HTML button's onclick attribute: function AddFbLikes() { $('#fbform').on('submit', function(e) { e.preventDefault(); // stop form submission $("input:checkbox:checked").each(function(i ...

Utilizing Webpack to Load Jquery

I developed an npm package named ABC, which I am currently testing in a create react app. This package utilizes Webpack and has a dependency on another package called DEF, which ultimately relies on Jquery. However, upon loading my create react app, I enco ...

The issue of the jQuery ajax script being inadvertently reloaded is persisting even after

I've successfully integrated a bootstrap modal and included a .js file that contains the necessary Ajax function. However, I have encountered an issue where the ajax function is triggered multiple times when the load more button is clicked multiple ti ...

The issue of `Console.log` displaying as undefined arises after subscribing to a provider in Ionic3

In the process of implementing the Spotify api into my Ionic 3 app, I encountered an issue where the data retrieved appears as undefined when attempting to log it. Let me share some code and delve deeper into the problem. Here is the function getData() tha ...

What is the process for determining the files array in the nx dep-graph?

With each new release of NX v16.1.4, the file node_modules/.cache/nx/nxdeps.json is created. The structure of this file differs from the one generated by nx graph. In previous versions up to 16.1., the file contained an array named nodes.<app/lib>.d ...

Tips on resizing images within a container to maintain aspect ratio

I am trying to create a layout with a flex container containing 2 divs - one with an image that floats left, and the other with some paragraphs floating right. How can I make sure that the image scales alongside the paragraphs while maintaining its aspect ...

What is the best way to load a partial in Rails asynchronously with AJAX?

I am currently using the following code to load a partial when I reach the bottom of a div containing a table: $(document).ready(function () { $("#pastGigs").scroll(function () { if (isScrollBottom()) { $('#pastGig ...

Issue with scrollTop not functioning when using onclick on an <a> tag within a div

After various attempts and research online, I am still experiencing erratic scrolling behavior with the scrollTop function. My goal is to scroll within a specific div when clicking on links. The content of my div: <div id="test" style="height:400px; o ...

Using ObjectIDs in MongoDB may be successful, however, it may not function properly in Mongoose

The desired effect is successfully achieved by the first code snippet shown below: //in mongodb console: db.collection.update({"username":"name"}, {$pull : { "task" : { "_id" : ObjectId("55280205702c316b6d79c89c")}}}) However, the second code snippet wri ...

Is there a way to identify the ID of a button using Javascript specifically in Internet Explorer and Safari browsers?

Within my code, there lies a directive that contains the attribute on-blur = blurFunc($event). Imagine this scenario: I interact with a button bearing the id "myButton" located outside of the directive. How can I determine which specific button was clicke ...

What is the best way to check if an object exists in an array in JavaScript and update it if it does, otherwise add it as a new object in

I am working with an array of objects const target = [{name: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89fafbe2c9eee4e8e0e5a7eae6e4">[email protected]</a>', selected: false, alertType: 'max&ap ...

What are the steps for building modules using Vuex and fetching data using mapState()?

I've been experimenting with separating my Vuex code into modules, but I'm having trouble retrieving data using mapState(). What's the most effective approach for creating modules and utilizing mapping? Here's the structure of my stor ...

Clear previous loop data in PHP

I have a "show recent" pictures div on my website that I want to refresh every 20 seconds to display a new picture. However, the issue is that my current ajax call refreshes instantly instead of after 20 seconds and it fails to delete the previous data, re ...

Stop the Form from Submitting When Errors are Present

In the midst of explaining my issue, I must first share details about a form I'm developing. It's a Registration form where upon submission by clicking Submit, users won't immediately reach a Successfully Registered page. Instead, they' ...

Submit an Ajax form to process data in PHP upon selecting a radio button

I am troubleshooting an issue with a form that is not submitting data to processor.php for processing and storing responses in a database. Ensuring that the form submission does not cause a page refresh is crucial, as there is an iframe below the form tha ...

Is there a tool that can automatically arrange and resolve TypeScript dependencies, with or without the use of _references.ts file?

Currently, I am working on understanding the new workflow for "_references.ts" and I feel like there is something missing when it comes to using multiple files without external modules in order to produce correctly ordered ".js" code. To start with, I took ...

Ionic3 footer using ion-tabs

Is there a way to create a common footer for all pages with 5 buttons, where the first button is selected by default? The page opened by this first button should have three tabs. I have already created the tabs but am unsure how to add the footer without r ...

Managing Visual Studio Code Extension Intellisense: A Guide

I am looking to create an extension I recommend using "CompletionList" for users. Users can trigger completion by running "editor.action.triggerSuggest" The process of my extensions is as follows: Users input text If they press the "completion command," ...