0

Let's say I have a few divs with IDs like "div1", "div2", "div3" and so on.

What I am doing now is:

document.getElementById('#div1').value='something';
document.getElementById('#div2').value='something';
document.getElementById('#div3').value='something';

but this gets annoying if I have like 30 divs. I'm trying to use "for" but it's not working:

for(var i=1; i<31; i++) {
    document.getElementById('#div'+i).value='something';
}

I'm getting the same thing when I use the .val() function (jQuery).

What am I doing wrong in this case, guys? :)

3
  • 1
    Are you adding the same value for each div? Commented Jul 7, 2013 at 15:29
  • 2
    Don't add the # in the getElementById argument Commented Jul 7, 2013 at 15:30
  • 1
    Divs don't have a value attribute. They have an innerHTML Commented Jul 7, 2013 at 15:31

3 Answers 3

2

You have a few things wrong. first, don't use # in getElementById(). second is that div elements doesn't have .value attribute, use innerHTML instead.. the third is that you're trying to access multiple elements by their id instead of creating a class shared by all of them. Code example:

HTML:

<div id="div1" class="myDiv"></div>
<div id="div2" class="myDiv"></div>
<div id="div3" class="myDiv"></div>
<div id="div4" class="myDiv"></div>
<div id="div5" class="myDiv"></div>
<div id="div6" class="myDiv"></div>
...

jQuery: (tagged in question - easiest example)

$(function(){
    $('.myDiv').text('something');
});
Sign up to request clarification or add additional context in comments.

1 Comment

My example was not very good just for you guys to understand what I was doing. Everything is working fine now. Thank you, Yotam!
0

You may use jquery each function but first you need to declare an array of div IDs for which you want to assign the value.

jQuery.each( [ "one", "two", "three", "four", "five" ], function() {
$('#' + this).text('value');
});

Or as said by Yotam, you may give a common class and just write

$('.className').text('value');

1 Comment

its so hard to get even a singe thumbs up. [phew]
0

You could do something simple like this:

<html>
<head>
    <title>Sample</title>
    <script type="text/javascript">
        function textDiv() {
            var totalDivs = document.getElementsByTagName("div").length 
            for(var i =0; i<totalDivs; i++)
            { 
                document.getElementById("div" + [i]).innerHTML = "Some Thing as a Text"

            }

        }
    </script>
</head>
<body onload="textDiv();">
    <div id="div0"></div>
    <div id="div1"></div>
    <div id="div2"></div>
    <div id="div3"></div>
    <div id="div4"></div>
</body>
</html>

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.