-1

Firstly I added the numeric id to most of my div class="line"

var adder = document.getElementsByClassName("line");             
for(var i = 0 ;i<adder.length;i++){         
    adder[i].id=i;
}

How to remove the divs which id is larger than, for an exaple, 10?

I fell into trouble when using parameter as the id in JS. It seems that it's illegal to write like this document.getElementsById(i);

PS: Is that appropriate to set id as pure Arabic numbers?

Darklizard
  • 377
  • 4
  • 17
  • *" It seems that it's illegal to write like this `document.getElementsByClassName(i)`"* You are setting the **ID** to `i`, not the **class**. It's not illegal to write such code, but if there is no element with *class* `i`, it will return an empty list. As for your question, you select the elements by class again (`.getElementsByClassName("line")`, iterate over the elements (like you already do) and compare the element's ID against `10`. – Felix Kling Jun 28 '13 at 08:47
  • @Felix Kling sorry I copied code and forgot to make modification... – Darklizard Jun 28 '13 at 08:49
  • document.getElementById(i.toString()) – hazzik Jun 28 '13 at 08:50
  • This works fine: http://jsfiddle.net/x2cMj/. It's quite the same no ? – Ricola3D Jun 28 '13 at 08:58
  • And about pure number IDs: http://stackoverflow.com/questions/7987636/why-cant-i-have-a-numeric-value-as-the-id-of-an-element – Ricola3D Jun 28 '13 at 08:59

2 Answers2

1

Try this fiddle

http://jsfiddle.net/yxCEb/

It's

adder.item(i);
yardarrat
  • 280
  • 3
  • 14
0

I am guessing what you are trying to do is not add ids above the number 10? If that's the case then why not just do:

var adder = document.getElementsByClassName("line");             
for(var i = 0 ;i<10;i++){         
    adder[i].id=i;
}

If you want to do this as a seperate operation for some reason then:

var adder = document.getElementsByClassName("line");             
for(var elem in addr){         
    if(parseInt(addr[elem].Id) > 10){
       element = document.getElementById(addr[elem].Id);
       element.parentNode.removeChild(element);
    }
}
reggaemahn
  • 6,272
  • 6
  • 34
  • 59
  • @hazzik Unfortunately it's not. For(each) loops work different in javascript. – reggaemahn Jun 28 '13 at 09:16
  • @hazzik Alright my dear friend. Here's a fiddle with your suggestion (only elem instead of addr[elem]) http://jsfiddle.net/VC95x/2/ and here is one with my answer: http://jsfiddle.net/KzdJN/3/ You can see for yourself which one works. I suggest you read the answer once more. The first bit of code is to suggest that there is a way to NOT have ids above 10 at all. The second bit of code is for when you have added ids above 10 and now want to remove them. PS. I know about the uppercase in 'Id'. I was typing on a mobile device and I think that is something that the OP could easily figure out – reggaemahn Jun 28 '13 at 10:37