I would like to set attributes on all elements that id starts with "id-" followed by a number [e.g. id="id-0", id="id-1) and so on]. I thought about something like this:
<script type="text/javascript" >
function Prepare() {
var = 0
while(document.getElementById("id-{var}")) {
document.getElementById("id-{var}").setAttribute("rows", "60");
var += 1
}
</script>
How can i set a var like this in JavaScript?
asked Feb 6, 2013 at 21:41
Registered User
2,0124 gold badges16 silver badges15 bronze badges
2 Answers 2
this should accomplish the task:
<script type="text/javascript" >
function Prepare() {
var ct = 0
while(document.getElementById("id-"+ct)) {
document.getElementById("id-"+ct).setAttribute("rows", "60");
ct += 1
}
</script>
alternatively:
<script type="text/javascript" >
function Prepare() {
for(var ct = 0;document.getElementById("id-"+ct);ct++) {
document.getElementById("id-"+ct).setAttribute("rows", "60");
}
</script>
answered Feb 6, 2013 at 21:44
ierdna
6,3739 gold badges56 silver badges91 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
ierdna
ct += 1 is equivalent to ct = ct + 1 or ct++
T.J. Crowder
@ user: Gosh, really?!?!?!
Shawn31313
@T.J.Crowder You learn something new everyday. Haha, but yeah. Its quite handy
T.J. Crowder
@Shawn31313: My comment might have been sarcastic. ;-)
Depending on compatability you could use querySelectorAll():
function Prepare(){
var els = document.querySelectorAll("[id^=id]");
for(var i=0; i<els.length; i++){
els[i].setAttribute("rows", 60);
}
}
answered Feb 6, 2013 at 21:55
Chase
29.6k1 gold badge52 silver badges49 bronze badges
Comments
lang-js
if (document.getElementById("id-"+variable)){ /** do stuff */};