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? :)
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');
});
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');
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.