What is the best way to assign a data attribute value based on an element's index using jQuery?

I am dealing with multiple sibling elements that are added dynamically or manually using JS. Each element has a data attribute called "data-sec_number" with a number value that increments by one for each subsequent element down the page. Currently, I am manually assigning these values. For example:

<div class="container">
<div class="row resource_sec" data-sec_number=1>
<div class="content sec_number" data-sec_number=1></div>
</div>

<div class="row resource_sec" data-sec_number=2>
<div class="content sec_number" data-sec_number=2></div>
</div>

<div class="row resource_sec" data-sec_number=3>
<div class="content sec_number" data-sec_number=3></div>
</div>
</div>

I am trying to figure out how to automatically set the value of the "data-sec_number" attribute to match the index of the .resource_sec element within the .container. For instance, the 3rd .resource_sec element should always have a "data-sec_number" value of 3. Additionally, I have a child element of .resource_sec called .sec_number, which also has the same data attribute that should reflect the value of its parent.

The JS code snippet I have been experimenting with is:

var items = $('.container .resource_sec');
var lastItem = $('.container .resource_sec:last');
var index = items.index(lastItem);

$('.resource_sec').attr('data-sec_number', index);
$('.sec_number').attr('data-sec_number', index);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row resource_sec" data-sec_number=1>
    <div class="content sec_number" data-sec_number=1></div>
  </div>

  <div class="row resource_sec" data-sec_number=2>
    <div class="content sec_number" data-sec_number=2></div>
  </div>

  <div class="row resource_sec" data-sec_number=3>
    <div class="content sec_number" data-sec_number=3></div>
  </div>
</div>

Answer №1

This line holds a specific significance

$('.resource_sec').attr('data-sec_number', index);

It is intended to assign a value to the attribute. To target a particular index, you can utilize the following statement:

$('.resource_sec[data-sec_number=' + index + ']')

or

$(`.resource_sec[data-sec_number=${index}]`)

In case you are utilizing ES6


UPDATE:

If you wish to introduce a new element using jQuery, try the following:

var container = $('.container')
var newElement = $('<div class="row resource_sec"></div>').appendTo(container)

Afterwards, you can determine the index of the new element by applying it to the index method, as per the jQuery documentation:

When .index() is used on a set of elements and a DOM element or jQuery object is supplied, .index() delivers an integer showing the position of the supplied element in relation to the original set.

var index = container.index(newElement)

To include the index in the new element's attribute:

newElement.attr('data-sec_number', index)

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 form a string from a chunk of text that includes the """ symbol within it?

I have come across a block of HTML code that contains form action elements and multiple occurrences of quotation marks. Is there a method to convert the entire block into a string? public string methodName() { return @ " text goes here.. blah blah ...

Trouble with Angular Charts: Data Reading Issue

Trying out chart.js for the first time and encountered an issue where the chart is not able to read data from the model. Previously, I had an error message of Error: $injector:modulerr Module Failed to instantiate module chart.js. This was fixed by switch ...

What is the best way to horizontally align Bulma's level items on smaller screens?

My website's footer features a level layout with left and right sections that follow the guidelines provided in theBulma docs. Everything looks good on larger screens. However, on smaller screens, all items in the right section are stacked vertically ...

The alert message fails to appear during an Ajax request

I'm having trouble understanding why the Ajax function in this code snippet is not triggering the success or error functions: function get_cust_key(custid) { $.ajax({ type: "POST", url: 'http://localhost/Test/index.php/getCust ...

Exploring the world of flexbox and experimenting with implementing flex-wrap at a specific breakpoint

I am working on a layout that includes a module containing various content. My goal is to have the progress bar, along with the labels "parts" and "projects," positioned underneath an image and expand to the full width of the module when the window size go ...

Modify a database entry by updating the price to include or exclude taxes based on the selected radio button option

I am working on developing a checkout form that includes radio buttons at the top. One button is meant to display prices without tax when selected, and the other to show prices with tax included. <form id="f-p" method="post" action="#####"> ...

Insert a hyperlink button using InnerHtml

I am facing an issue with displaying a list item that contains a tab and a link button: <li runat="server" id="liActivityInvoices"><a href="#tabActivityInvoices">Invoices</a><asp:LinkButton runat="server" ID="btnLoadInvoice" OnClick=" ...

How can I utilize PHP to generate several tables within a single database?

I need some guidance on creating multiple tables within the "new" database. I'm curious if it's possible to include PHP code inside the query to generate table names dynamically. Any help would be greatly appreciated. Thank you in advance. <? ...

HTML dropdown menu to trigger an action with the submitted URL

I need assistance creating a menu of options with corresponding URL actions. Here is the structure I have in mind: <form> <select> <option value="1">1</option> <option value="2">2</option> <option value="3 ...

Understanding Arrays in Angular JSIn this article, we

I am new to working with Angular JS. Currently, I am populating an array and attempting to showcase its contents on the HTML page using ng-repeat. $scope.groupedMedia = []; // Elements are being added through a for loop. $scope.groupedMedia[year].push(r ...

Has anyone come across an XSLT that can effectively convert Apple Pages files into high-quality HTML?

When Apple’s word processor/DTP app Pages saves its files, it does so as zipped folders with an XML file containing the content and attachments like images stored as separate files. I am interested in converting this content into HTML format, using < ...

Deselect the tick marks on the dropdown box for material selection

I need help implementing a function for a click event that will unselect all items. <mat-autocomplete [panelWidth]='290' panelClass="myPanelClass"> <mat-option *ngFor="let item of items" [value]="item.name&qu ...

Having trouble making JSON work alongside Ajax and jQuery?

In my JavaScript, I have the following code snippet... $.ajax({ type: 'POST', url: 'http://www.example.com/ajax', data: {email: val}, success: function(response) { alert(response); } }); The PHP fil ...

Rendering child components in Vue.js with access to parent data

I have a main component in Vue.js with the following structure: <template> <ul class="list-group"> <li class="list-group-item" v-for="item in items"> <div class="row"> <div class="col-md-6"> ...

Discover the best way to showcase items within an arrayList using dual CSS styles!

I'm currently working on a project that involves an arrayList with two names: Bob and Steve. I have the requirement to display them in different colors, where Bob should be displayed in green and Steve in red. Component.CSS .Bob{ font-weight:bold; ...

Error message occurs when creating a pie chart with invalid values for the <path> element in Plottable/D3.js

For those who need the code snippets, you can find them for download here: index.html <!doctype html> <html> <head> <meta charset="UTF-8"> <!-- CSS placement for legend and fold change --> </head> <body ...

What is the best way to eliminate alternative styling from a chart component in C#.NET?

I've encountered an issue with a stacked chart component on a c#.net webform from the MS Chart Control Library. Initially, I dragged the control onto the design surface and then proceeded to edit the source html (.aspx page) to assign the element a cs ...

"Troubleshooting: Issues with jQuery's .on method when used with dynamically added

I have a large number of <button class="lb"> <div class="l"></div> <div class="c">2</div> <div class="r"></div> </button> Some of these buttons are present in the initial DOM when the page loads, whi ...

Determine a comparative measurement using specific numerical values

I am currently in the process of creating a webpage and I want to ensure that it is responsive by adjusting certain values based on the width of the viewport. Specifically, I have a DIV element that I want to split into 2 columns. For smaller screens (min ...

Tips for creating a dynamic animation: How to make a div fall from the top and rotate

Hey everyone, I'm working on creating an animation where a phone falls from the top and then rotates and skews to give the illusion of a 3D shape when it reaches the bottom. However, I'm facing an issue with flickering in the animation when it hi ...