A
A
Arthur Koch2012-04-26 11:14:10
JavaScript
Arthur Koch, 2012-04-26 11:14:10

Get the maximum value of an attribute?

Given the following DOM structure:

<div class="tags">
<span id="tag_4" class="tag">tagname</span>
<span id="tag_1" class="tag">tagname</span>
<span id="tag_6" class="tag">tagname</span>
<span id="tag_3" class="tag">tagname</span>
<span id="tag_15" class="tag">tagname</span>
<span id="tag_8" class="tag">tagname</span>
</div>

Task:
Get the maximum value of id+1 (in this case it should be 16, but the order and fragmentation can be random).
If no elements are found, get one. <div class="tags">

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
Andrey Burov, 2012-04-26
@dudeonthehorse

tags=document.getElementsByClassName('tags');
for (x in tags){
  for (y in tags[x].childNodes){
    tags[x].childNodes[y].id.... ну а дальше разберетесь
  }
}

or do you need the whole code?

N
Nesvet, 2012-04-26
@Nesvet

Are you using jQuery?
If yes, then:
var maxid = 1;
$(".tags").children().each(function () {
maxid = Math.max(maxid, parseInt($(this).attr("id").replace(/[^\d]/g, ""))+1)
});

S
spmbt, 2012-04-26
@spmbt

tags = document.querySelectorAll('span[id^=tag]');
var n =1;
for(var i in tags){
  var n2 = Number(tags[i].id.replace(\tag_/,'') );
  if(n2) > n)
    n = n2;
}

S
serjoga, 2012-04-27
@serjoga

why not use Math.max?

var a = [2,3,1,10,25,2,4,7], maxValue = Math.max.apply(Math, a);

alert(maxValue)

PS: it is clear that first you need to take all the necessary shniks and convert them to a numeric type, something like
var oneElementOfArray = Numbser(span.id.substr(4)) || 0

M
MT, 2012-04-27
@MTonly

If the attribute is onlyid used to store a numeric identifier, then it's more appropriate to use HTML5 attributes prefixed with to store arbitrary non-displayable data:data-

<ul class="tags">
  <li data-id="1">firefox</li>
  <li data-id="2">webkit</li>
</ul>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question