Each element is being adorned with the Ajax success function class

Currently, I am in the process of creating an Ajax function to integrate search features into my project. The search function itself is functioning properly; however, within the success: function, I am encountering an issue. Specifically, I am attempting to add a class to the entire searched element, but instead, the class is being added to every element.

$('#id_search_tag').keyup(function(e) {
  $.ajax({
    url: "{% url 'searchTag' %}",
    data: {
      'w': $('#id_search_tag').val(),
    },
    method: 'get',
    dataType: 'json',
    success: function(response) {
      for (result of response.results) {
        $('#tags_list').prepend(`
    <div id="tags-browser" class="grid-layout">
        <div class="mySearchedTags">
               <div class="d-flex jc-space-between ai-center mb12">
                <div class="flex--item">
                    <a href="/answers/tag/tag" class="post-tag" >${result.tagName}</a>
                </div>
            </div>
        </div>
    </div>
       `)
      }
    }
  })
})
<div id="tags_list">
  <div id="tags-browser" class="grid-layout">
    <div class="mySearchedTags">
      <div class="d-flex jc-space-between ai-center mb12">
        <div class="flex--item">
          <a href="/answers/tag/tag" class="post-tag">{{tag}}</a>
        </div>
      </div>
    </div>
  </div>
</div>

Upon inspecting the elements, it becomes evident that

<div id="tags-browser" class="grid-layout">
is appearing on each and every element:

<div id="tags-browser" class="grid-layout">
    <div class="mySearchedTags">
  ....
   ....
    ....

<div id="tags-browser" class="grid-layout">
    <div class="mySearchedTags">
  ....
   ....
    ....

My objective is to apply this class only to the first element, as illustrated below:

<div id="tags-browser" class="grid-layout">
    <div class="mySearchedTags">
        ....
        ....

    <div class="mySearchedTags">
        ....
        ....

    <div class="mySearchedTags">
        ....
        ....

</div>

Despite numerous attempts, the class is still getting added to all elements. Any insight or guidance on correcting this behavior would be greatly appreciated!

Answer №1

Try moving the first div outside of the loop for better performance. I have utilized map, join, and destructuring of tagName to enhance the code's readability

$('#tags_list').prepend(`<div id="tags-browser" class="grid-layout">
  ${response.results.map(({tagName}) => `<div class="mySearchedTags">
            <div class="d-flex jc-space-between ai-center mb12">
                <div class="flex--item">
                    <a href="/answers/tag/tag" class="post-tag" >${tagName}</a>
                </div>
            </div>
        </div>`).join("")}
    </div>`)

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

Trouble with HTML and CSS design layout

I'm struggling to create a responsive design for my webpage. The layout should consist of black blocks that display images. Ensuring the layout adapts to different screen sizes is proving challenging. It needs to maintain its shape on smaller screens ...

Wordpress Custom Post Type with a Sleek Slider Plugin

I am currently using a static slick slider to display testimonials on my website. Instead of hardcoding the testimonials, I want to fetch them from a WordPress custom post type that I have created. Can someone guide me in the right direction: <section ...

Delete all HTML functionalities

Is there a way to strip HTML functions when using a text area so that the content shows as plain text in a new post (div)? For example, if I type "Hello", I want it to appear as "< b > Hello < b / >", showing the whole code. Here is the code ...

AngularJS default ngOptions for parent and child models

Is there a way to set default ngOptions through parent/child models? Here, the OP demonstrates using ngOptions with parent/child relationships. template <select ng-model="x.site" ng-options="s.site for s in data"></select> <select ng-mode ...

Implementing conditional color parameter using Vuetify on an element

In my Vuetify project, I'm utilizing the built-in color parameter and predefined colors. My goal is to dynamically change the component's color based on the data it receives. For example, if complete: true, then the color should be green. Here&a ...

The last javascript file that was included has been overlooked

When using jqplot, I noticed that the last included plugin is being ignored. If I switch their positions, the first to last one works while the last one does not. There are no errors in the console to indicate what might be going wrong. Moving the canvasOv ...

What is the best way to retrieve and display the heading of the current section that is being viewed using Bootstrap Vue's ScrollSpy feature?

I am currently using the Bootstrap Vue Scrollspy feature in my project with Nuxt js. The elements are correctly referenced and are successfully spying on the content. What I would like to achieve is having the ability to update a specific div with the curr ...

Styling each list item individually, without interdependence

I am working on a ul that contains several list items comprised of h3s and lis with the "close" class. When I hover, I want to expand the letter spacing on the h3s, but the items with the close class also expand. I have tried using nth child selectors in ...

Is it possible to use JavaScript to save and preserve the current state of a webpage?

I'm looking for a way to retrieve the entire content of a webpage using JavaScript and then send it to a server script for saving. This action should be triggered after the user has made some changes to the page using AJAX and other JavaScript tools. ...

Creating a custom design for legends in Chart.js

I'm currently working on a project using chart.js and I'm trying to customize the label/legend styling for my chart. My goal is to replace the rectangular legend with a circular one. I've come across the suggestion of creating a custom legen ...

Exploring the wonders of Jasmine coding with jQuery

I am relatively new to conducting Jasmine tests. I have a basic understanding of how to install it and use simple commands like toEqual, toBe, etc. However, I am unsure of how to write test code for this particular jQuery function using Jasmine. if ($(&ap ...

Vue - Display components next to sidebar

Having an issue with the vue-sidebar-menu. The sidebar is appearing over the components instead of beside them. Here is a screenshot of the problem: https://i.sstatic.net/cVgI6.jpg <template> <div id="app"> <sidebar-menu :menu="menu" ...

Turn on/off the webGL Context in webGL/three.js

I am currently working on an exciting project using three.js, and so far everything is going according to plan. The project involves displaying various meshes in different canvases, which has led me to encounter a particular issue. My goal for the project ...

Page flickers when jQuery is used to scroll to an element

One issue I have encountered is with a link that, when clicked, should scroll down to a specific element on the page. However, every time I test this feature, there seems to be an inconsistency where the page may momentarily flash before scrolling as inte ...

Combine the values of two text fields from separate input fields to populate a new text field across several lines

https://i.sstatic.net/fp8aZ.png I am seeking a way to automatically calculate the total cost by multiplying the quantity and unit cost values for each line entered. Despite my attempts with the jQuery script provided below, I have been unable to achieve t ...

Unexpected behavior with scrollTop

Note Reopening bounty as I forgot to award it last time. This question has already been answered by Master A.Woff. I am looking for a way to automatically scroll to a specific row when a user expands it, so that the content is immediately visible witho ...

Dealing with multiple jQuery ajax requests - strategies for managing them

Whenever I click the button quickly while there is jQuery Ajax loading, it seems to get stuck. How can I manage multiple requests being fired at the same time? What is the solution for the following: Cancel/abort all previous requests and only handle th ...

JQuery Ajax Success does not fire as expected

I am facing an issue with my ajax call where the success function is not getting triggered. My controller gets called and the code executes without any errors. However, since my method returns void, I am not returning anything. Could this be the reason why ...

Detecting the insertion of a DOM element with jQuery: locate a particular element

I am interested in learning how to detect when a SPECIFIC element is added to the DOM and then take action based on that. Initially, after the DOM has finished loading, there is a div(.myElement) that gets loaded much later: <div class="container"> ...

Take out the class right after slideUp begins but before it completes (using callbacks)

I am delving into Jquery for the first time, and I have encountered an issue with this code snippet. The HTML can be found in the fiddle provided. Challenge The problem arises when using the slideup callback function as it waits 300 seconds before removi ...