I have couple of divs like
<div id="rg_dia_0">
zdszczxvzxvzxvc
</div>
<div id="rg_dia_1">
dfgdZXcZC
</div>
<div id="rg_dia_2">
hfhgjhgjdj
</div>
I need javascript to fetch all the divs and delete the content. I think we can use regex to match the ids as only the number that is changing.
As said by Sam in Javascript it can be
for (var i = 0; i <= 2; i++) {
document.getElementById("rg_dia_" + i).innerHTML = "";
}
Something like this can easily be done with jQuery. I would strongly encourage you to learn it.
$('div').each(function() {
$(this).html('');
});
$('#id').html(newContent);
try:
$("div[id^='rg_dia_']").html("");
see this for wildcard attribute selection in jQuery.
for (var i = 0; i <= 2; i++) {
$("#rg_dia_" + i).html("");
}
to clarify; the above obviously requires the use of jQuery, as l.devries so blatantly down-voted as an act of true adulthood and surely not be considered as trolling since the explanation as of why had to be requested first. glad to have people like you on-board!
Related
I have a feeling this is pretty simple, but my JS is not very good.
I have a div class
<div class=" foo1 foo2" style="top: 0px;">
I can see in chrome that it this div has an attribute set like this:
.foo2
{
position: fixed;
width: 100%;
}
I'm trying to use JS to adjust the attributes of foo2, but I don't know how to get at it.
var changeFoo = document.getElementById ('foo2');
changeFoo.position = "relative";
How do I call foo2.position and change it?
Try this:
Its a pure javascript solution.
function update_this_css(matchClass) {
var elems = document.getElementsByTagName('*'), i;
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')
> -1) {
elems[i].style.position = "relative";
}
}
}
update_this_css('foo2');
You can do it as:
var foo= document.getElementsByClassName('foo2');
for(var i=0;i<foo.length;i++){
foo[i].style.position='relative';
}
You are trying to get the JS to identify an element using its ID ('foo2') which you have not set. If you want to use a class name instead you must use:
document.getElementsByClassName
else you must give your element your desired ID.
Another problem is that you simply have:
changeFoo.position
where as you need to use:
changeFoo.style.position
To get your code to work, you need to loop through the results:
var divs = document.getElementsByClassName('foo');
for(var i=0; i<divs.length; i++) {
divs[i].style.position='fixed'
}
The easiest way I found so far is to use jQuery because regular javascript is so much longer and harder to write. Get a JS library one at jquery.com Learn jQuery once and say thanks to yourself forever :) You can use CSS selectors to get elements without any IDs.
Then use it like this.
$('.foo2').css('position', 'relative');
http://api.jquery.com/css/
I have a list of texts and I want to change their innerHTML. how can I do that by javascript if I have thousands of li tag (whose data come from database)?
<div>
<ul>
<li>a</li>
<li>as</li>
<li>asd</li>
<li>asds</li>
<li>asdsa</li>
<li>asdsad</li>
<li>asdsadz</li>
<li>asdsadzc</li>
....
.....
</ul>
</div>
-Thanks.
Update
JS code being used:
function a(){
var parent = document.getElementById("z");
var i = 0;
for(i = 0; i <= parent.children.length; i++){
if(parent.children[i].tagName == "LI"){
if(i%2!=0){
parent.children[i].innerHTML="ok";
}
}
}
}
document.onload=a(); // this didn't work. so I called the function in body tag instead of that.
<body onload="a();">
Have you tried using getElementsByTagName ? Sonds like it would help you find the elements you're trying to work with.
Edit
If you can give an Id to the UL element that holds the li's you're trying to process, you could do something like this:
var parent = document.getElementById("yourID");
var i = 0;
for(i = 0; i < parent.children.length; i++){
if(parent.children[i].tagName == "LI") {
//do what you want...
}
}
EDit 2
You have to change the last line on your script:
document.onload=a();
With this one: window.onload=a;
That'll get your function to execute on the onLoad event. Note that there might be some crossbrowser incompatibility, I would suggest researching a bit on how to execute functions on the onload event on a crossbrowser manner, or just adding this to your body tag:
<body onload="a();">
Given the - not so far fetched - precondition you wish to use jQuery, you can select them and iterate over them with "each".
$("li").each(
function() { $(this).html("changed content"); }
);
If you are not using jQuery, using a js-library that helps you out with the quircky dom is probably not a bad idea...
The general idea
Select nodes
Iterate and change html
is always the same.
I'm wondering if it's possible for a script to enable/disable all input elements on the page with some sort of toggle button.
I googled it but didn't find anything too useful except for this:
http://www.codetoad.com/javascript/enable_disable_form_element.asp
but I'm not sure how to edit it for the toggle.
Something like this would work:
var inputs=document.getElementsByTagName('input');
for(i=0;i<inputs.length;i++){
inputs[i].disabled=true;
}
A working example:
$().ready(function() {
$('#clicker').click(function() {
$('input').each(function() {
if ($(this).attr('disabled')) {
$(this).removeAttr('disabled');
}
else {
$(this).attr({
'disabled': 'disabled'
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<input type='text'></input>
<input type='text'></input>
<input type='text'></input>
<div id='clicker' style='background-color:#FF0000; height:40px; width:100px;'></div>
Here is a function to toggle all inputs on the page:
function toggle_inputs() {
var inputs = document.getElementsByTagName('input');
for (var i = inputs.length, n = 0; n < i; n++) {
inputs[n].disabled = !inputs[n].disabled;
}
}
It works by using the logical NOT operator (the exclamation point), which returns the opposite of the operand. For example, !true will return false. So by using !inputs[n].disabled, it will return the opposite of what it's currently set to, thereby toggling it.
If you need code to bind the click event to the button:
document.getElementById('your_button_id').onclick = toggle_inputs;
You can also use addEventListener, but see the linked page for more information, including compatibility with Internet Explorer. The code I gave above should work across all browsers with no trouble.
for (var i = 0; i < document.getElementyByTagName('input').length; i++) {
document.getElementsByTagName('input')[i].disabled = 'disabled';
}
http://code.google.com/p/getelementsbyclassname/
^^Robert Nyman has a "get elements by class" script. Basically you'd just assign all those input elements to the same class, and then do something like:
//Collapse all the nodes
function collapseNodesByClass(theClass){
var nodes = getElementsByClassName(theClass);
for(i = 0; i < nodes.length; i++){
nodes[i].style.display='none';
}
}
This is a piece of code I'm actually currently using to collapse everything with a given class name (it uses the script I mentioned above). But in any case I think the key to your problem is being able to refer to multiple elements at once, which that script will help you with.
Also the link in your question didn't work for me :(.
I have a question about the class, and give the class a specific id.
For example I've got a html code like this:
<div class="test">text1</div>
<div class="test">text2</div>
<div class="test">text3</div>
<div class="test">text4</div>
<div class="test">text5</div>
My question is how can I add an id by each .test class.
I thought something like this in Jquery:
var i = 1;
$('.test').each(function(){
$('.test').attr('id','id_'+i+'');
i++
});
This doesn't work I think it's something with .closest() or .next()
to solve this problem.
Regards,
Frank
EDIT:
I solved the problem by myself the answer is:
$('.test').each(function(){
$(this).attr('class','test').attr('id','id_'+i+'');
i++;
});
No reason to make a counter, .each() comes with one built in.
$('.test').each(function(i){
$(this).attr('id','id_'+i+'');
});
Use $(this) to refer to the current element the in callback function:
var i = 1;
$('.test').each(function(){
$(this).attr('id','id_'+i);
i++
});
Much faster and simpler like this:
$('.test').each(function(i){
this.id = 'id_' + i;
});
There's no need for .attr() when setting or getting the id of an element.
Or if you wanted the numbers to start with 1, do this:
$('.test').each(function(i){
this.id = 'id_' + (i + 1);
});
You were on the right path:
var i = 1;
$('.test').each(function(){
$(this).attr('id','id_'+i+'');
i++
});
Use this jQuery instead:
var i, $test = $('.test'), tl = $test.length;
for (i = 0; i < tl; i++) {
$test.eq(i).attr('id','id_'+i+'');
}
As i is incremented in the for loop, you select the specific element you want to give the i based id with .eq(i).
I want to go through all the elements on a page using Javascript and see if they have a property set. Is there an easy way to do this, or do I have to use a recursive solution?
You can use:
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
//do something to each div like
divs[i].innerHTML = "something new...";
}
To find a property in one or more of all divs on a page:
var divs = document.getElementsByTagName("div"), i=divs.length;
while (i--) {
if (divs[i].getAttribute([yourProperty]) === 'yourValue'){
//do something
}
}
[edit october 2022] Very old answer. Today I would advise to use a css selector. For example:
const withStyle = document.querySelectorAll('[style]');
console.log(`Found ${withStyle.length} elements with style:\n${
[...withStyle]
.map(el =>`<${el.tagName}>: ${el.getAttribute('style')}`)
.join(`; `) }` );
<div style="color:#777">
<div style="color:red;background:#EEE">red</div>
<div>no color</div>
<div data-something>data-attribute</div>
<div style="color:green">green</div>
<span>Hello</span>
<h3 style="font-family:monospace">That's all folks</h3>
</div>
Using JS ES6 For ... of
for (elem of document.getElementsByTagName('div')){
elem.style.marginTop='20px'
}
You might also be able to use a selector engine such as Sizzle.
Steve