Agus Putra Dana
Agus Putra Dana

Reputation: 719

Get dynamic Id from dynamic elements

I have div element with dynamic Id.

<div id="parent">
    <div id="elmn1"></div>
    <div id="id-has-changed"></div>
    <div id="elmn3"></div>
    <div id="elmn4"></div>
    <div id="id-has-changed-by-user-from-input-field"></div>
</div>

All element id (except #parent) are editable by user from an input field, so the last child of #parent may has new id set by user.

I want to check the element with the highest number (4) at the last part of their id and I want to append a new element with the next id.

var nextId = "elmn" + (numberOfLastElement + 1);
var newElmn = document.createElement("div");

newElmn.id = nextId;
document.getElementById("parent").appendChild(newElmn);

In this paricular case the new element will has id="elmn5".

My question is, how to get numberOfLastElement?

Upvotes: 2

Views: 20402

Answers (3)

user796446
user796446

Reputation:

Updated

Final version of Fiddle

var myEl = document.getElementById('parent').children;
var highest = null;
var idName= null;

if (myEl){

for (var ii=0;ii<myEl.length;ii++){
     
     var temp = myEl[ii].getAttribute('id');
    
    
    var intval = temp.match(/\d+/g)
     
    
    if (intval !=null){
        
        if(intval>highest){
            
         
            highest = intval;
            idName = temp;
        }
        
        
    }
  

  }

}

console.log(idName);

Leaving the code below for historical info

Here is a working JSFiddle.

var myEl = document.getElementById('parent').children;
var count = 0;
      if (myEl) {
            var match = 'elmn';
            for (var ii = 0; ii < myEl.length; ii++) {
                var temp = myEl[ii].getAttribute('id');
                if (temp.indexOf(match) == 0) {
                    count++
                }
            }
        }
        alert('count is ' + count);

Upvotes: 2

PM 77-1
PM 77-1

Reputation: 13352

Something like this, assuming elmn prefix in all applicable IDs:

function MaxElemNo() {
  var prefix = "elmn";
  var parent = document.getElementById("parent");
  var elements = parent.querySelectorAll("[id^='"+ prefix + "']");
  var lastElemNo = 0;
  for (var i=0; i<elements.length; i++) {
     var el = elements[i].id;
     var num = + el.substring(prefix.length, el.length);
     lastElemNo = Math.max(lastElemNo, num) 
  }
  return lastElemNo;  
}    
console.log(MaxElemNo());

JS Fiddle

Upvotes: 1

laaposto
laaposto

Reputation: 12213

Here is the logic:

Get all the elements what have id="elmnx" where x=1,2, etc. $("[id*='elmn']")

Get the last of them. last()

Get its id.attr('id')

Substring to get the number at the end. substring(4)

Make it an int so that you can add +1. parseInt()

Try:

var numberOfLastElement=parseInt($("[id*='elmn']").last().attr('id').substring(4));

Upvotes: 2

Related Questions