0

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?

1
  • 1
    if (document.getElementById("id-"+variable)){ /** do stuff */}; Commented Feb 6, 2013 at 21:44

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

4 Comments

ct += 1 is equivalent to ct = ct + 1 or ct++
@ user: Gosh, really?!?!?!
@T.J.Crowder You learn something new everyday. Haha, but yeah. Its quite handy
@Shawn31313: My comment might have been sarcastic. ;-)
0

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);
    }
}

EXAMPLE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.