innerHTML and use of Array - javascript

I have several div tags trainingData0, trainingData1, trainingData2, etc that I am trying to use innerHTML to update text.
I am trying to refer to them with a for loop but it doesn't work. (even though trainingDataDiv does hold the correct value ie trainingData0 which DOES work if I type trainingData0.innerHTML )
Any advice? Thanks in advance.
<div id="trainingData0"></div>
---------------
for (var i=0; i<15; i++)
{
var trainingDataDiv = "trainingData" + i;
trainingDataDiv.innerHTML = data;
}

Answer by Robby Cornelissen in comments of my question :)
for (var i=0; i<15; i++)
{
var trainingDataDiv = document.getElementById("trainingData" + i);
trainingDataDiv.innerHTML = data;
}

So you don't have to change your max number when you change the number of elements:
//Get all elelemtns with ids that start with trainingData
var trainingDataDivs = document.querySelectorAll("[id^='trainingData']");
var data = "I'm training Data";
//iterate the elements we found earlier and update the data
for(var i = 0; i < trainingDataDivs.length; i++)
{
trainingDataDivs[i].innerHTML = data;
}
<div id="trainingData0"></div>
<div id="trainingData1"></div>
<div id="trainingData2"></div>
<div id="trainingData3"></div>
<div id="trainingData4"></div>
<div id="trainingData8"></div><!-- Note the gap in numbers -->
<div id="bob">I'm not training</div>
For more info see Attribute selectors and querySelectorAll

Related

JS exstract part of URL from multiple form fields

I have a form that has multiple fields all with the same class. These are populated with URL's that follow the same structure. I am trying to extract the same section from each URL. So far var res = x.split('/')[5]; will achieve this but only for the first URL. I can also use var x = document.querySelectorAll(".example") to change all the url's but I cannot find the correct way to combine both of these function. so far my code looks like this:
script>
function myFunction() {
var x = document.querySelectorAll(".example").innerHTML;
var res = x.split('/')[5];
var i;
for (i = 0; i < x.length; i++) {
x[i].innerHTML = res;
}
}
</script>
I have looked around but can't find a solution that fits. Thanks in advance for your help.
So loop over the HTML Collection, this is making assumptions based on code.
// Find all the elements
var elems = document.querySelectorAll(".example")
// loop over the collection
elems.forEach(function (elem) {
// reference the text of the element and split it
var txt = elem.innerHTML.split("/")[5]
// replace the text
elem.innerHTML = txt
})
<div class="example">1/2/3/4/5/a</div>
<div class="example">1/2/3/4/5/b</div>
<div class="example">1/2/3/4/5/c</div>
<div class="example">1/2/3/4/5/d</div>
<div class="example">1/2/3/4/5/e</div>
<div class="example">1/2/3/4/5/f</div>

Getting into all entries by querySelectorAll in JS

Yesterday, I've asked the same, by today I'm little more specific. I want to get those div values into the generated link, so link would be like: https://stackoverflow.com/value1 value2 value3
<div class="example">value 1</div>
<div class="example">value 2</div>
<div class="example">value 3</div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.querySelectorAll('.example');
var i;
for (i = 0; i < x.length; i++) {
x[i].innerText;
}
window.open('https://stackoverflow.com/'+x ,'_blank', "width=550, height=550");
}
</script>
All i'm getting is https://stackoverflow.com/[object NodeList]
Can you help me how to handle this?
All i'm getting is https://stackoverflow.com/[object NodeList] Can you
help me how to handle this?
Because x is still the nodeList and you are not assigning anything to x, you need another accumulator
var value = [];
for (i = 0; i < x.length; i++) {
value.push( x[i].innerText);
}
value = value.join(" "); //not sure why you need space delimited values
window.open('https://stackoverflow.com/'+value ,'_blank', "width=550, height=550");
Just having the line x[i].innerText; on its own returns the value of innerText but crucially you're not storing the result anywhere.
In the window.open() function the value of x is an object not a string.

Javascript - element.childNodes does not see an append.newchild

given the following:
<div ID="parent">
<div ID="child1">Children Stuff</div>
<div ID="child2">More Childish things</div>
</div>
<div ID="orphan">Whhhaa I want a mommy</div>
var p = document.getElementById("parent");
var c = document.getElementById("orphan");
p.appendChild(c);
var ch = p.childNodes;
var ln = p.children;
for(var i=0;i < ln.length; i++) {
console.log(ch[i]);
}
console.log(ln.length);
The console output provides:
<div ID="child1">Children Stuff</div>
<div ID="child2">More Childish things</div>
3
Here's where I am lost:
I need to obtain information out of each child node (including the new child). Naturally I won't be simply outputting it to a console, I need to perform some logic on other DOM elements that share similar IDs as the children.
Why doesn't the element.childNodes; call pick up on the new child?
Any help is appreciated.
The above is sample air-code so I apologize if the syntax is not 100%, but I'm hoping the point gets accross nonetheless.
You're looping over ln.length but reading ch:
for(var i=0;i < ln.length; i++) {
console.log(ch[i]);
}
That gets confusing very quickly, as ln has a length of 3 and contains the child elements. ch has a length of 6 and contains all elements (including 3 text elements with just line feeds).
This is really easy to see if you just add 2 more console logs:
console.log('ch',ch);
console.log('ln',ln);
As here: https://jsfiddle.net/mqhevnsu/
Because you mix childNodes and children. Try using only children:
var p = document.getElementById("parent");
var c = document.getElementById("orphan");
p.appendChild(c);
var ln = p.children;
for(var i=0;i < ln.length; i++) {
console.log(ln[i]);
}
console.log(ln.length);
<div ID="parent">
<div ID="child1">Children Stuff</div>
<div ID="child2">More Childish things</div>
</div>
<div ID="orphan">Whhhaa I want a mommy</div>
It just works if you fix the typos and become consistent in using p.children or p.childNodes:
var p = document.getElementById("parent");
var c = document.getElementById("orphan");
p.appendChild(c);
var ch = p.children;
for(var i=0;i < ch.length; i++) {
console.log(ch[i]);
}
console.log(ch.length);
jsfiddle

Get the id numbers (separatly) from the url and use it to select the id with that ID number (using jquery)

I am working on a website where I dont have any control on the code (functionality side. however even if I had the access I wouldn't be able to make any changes as I am a front end designer not a coder..lol). The only changes I can make is CSS, js.
What I am tring to do:
I got the url on the page like this:
www.test.com/#box1#box3#box5
(I am not sure if I can have more than one ID in a row. please advice. However thats how the developer has done it and I dont mind as there are no issues yet)
the page html
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<div id="box4"></div>
<div id="box5"></div>
I would like to take different ids from the URl and use it to hidhlight the divs with that ID (by addding a class name "highlight")
The result should be like this:
<div id="box1 highlight"></div>
<div id="box2"></div>
<div id="box3 highlight"></div>
<div id="box4"></div>
<div id="box5 highlight"></div>
I would like to learn the smart way of taking just the id numbers from the url and use it to select the div with that paticulat no.
just a quick explanation:
var GetID = (get the id from the URL)
$('#box' + GetID).addClass('highlight');
Try This...
var hashes =location.hash.split('#');
hashes.reverse().pop();
$.each(hashes , function (i, id) {
$('#'+id).addClass('highlight');
});
Working fiddle here
var ids = window.location.hash.split('#').join(',#').slice(1);
jQuery(ids).addClass('highlight');
or in plain JS:
var divs = document.querySelectorAll(ids);
[].forEach.call(divs, function(div) {
div.className = 'highlight';
});
There are various way to resolve this issue in JavaScript. Best is to use "split()" method and get an array of hash(es).
var substr = ['box1','box2']
// Plain JavaScript
for (var i = 0; i < substr.length; ++i) {
document.getElementById(substr[i]).className = "highlight"
}
//For Each
substr.forEach(function(item) {
$('#' + item).addClass('highlight')
});
//Generic loop:
for (var i = 0; i < substr.length; ++i) {
$('#' + substr[i]).addClass('highlight')
}
Fiddle - http://jsfiddle.net/ylokesh/vjk7wvxq/
Updated Fiddle with provided markup and added plain javascript solution as well -
http://jsfiddle.net/ylokesh/vjk7wvxq/1/
var x = location.hash;
var hashes = x.split('#');
for(var i=0; i< hashes.length; i++){
var GetID = hashes[i];
//with jQuery
$('#box' + GetID).addClass('highlight');
//with Javascript
document.getElementById('box' + GetID).className = document.getElementById('box' + GetID).className + ' highlight';
}

Get all the divs after a div and decrease by one their attribute

I have some divs that have an attribute: rowNumber.
one of them has an attribute: isOpen=1.
All the others that are after it have isOpen=0.
for example:
<div class="statusCell" isOpen="0" rowNumber="1">
I want to get all of the divs with class statusCell that are found after the div with isOpen=1, and decrease by one their rowNumber.
I need to do something like:
$('.statusCell[isOpen=1]').nextAll('.statusCell[isOpen=0]').each(function() {
var rowNumber = $(this).attr("rowNumber");
var newRowNumber = parseInt(rowNumber, 10) - 1;
$(this).attr('rowNumber', newRowNumber.toString());
});
but it doesn't work because:
$('.statusCell[isOpen=1]').nextAll('.statusCell[isOpen=0]').length
is zero..
a sample code is:
<td class="DesignedTableTD">
<div class="statusCell" style="cursor:pointer;" isOpen="0" rowNumber= "1">
<p style="display:inline;" class="yellow" title="fd">
<img alt="Active" src="#Url.Content("~/Images/play.png")" class="help"/>
</p>▽
</div>
</td>
any help appreciated!
nextAll selects next matching siblings of the selected element which is not the case here, you can use the index() method:
var $statusCell = $('.statusCell[isOpen]'),
$open = $statusCell.filter('[isOpen=1]'),
i = $statusCell.index($open);
$statusCell.filter(':gt('+i+')').foo();
// Decreasing attributes' value
// $statusCell.slice(++i).attr('rowNumber', function(_, value) {
// return +value - 1;
// });
Note that isOpen and rowNumber are not valid attributes, if the Doctype of the page is HTML5 you can use data-* attributes instead.
Alternatively...
var oStatCell = querySelectorAll(".statusCell[isOpen=1]");
for(i = 0; i < oStatCell.length; i++) {
var cStatCell = oStatCell[i].querySelectorAll(".statusCell[isOpen=0]");
for(j = 0; j < cStatCell.length; j++) {
cStatCell[j].setAttribute("rowNumber", String(parseInt(cStatCell[j].getAttribute("rowNumber")) - 1));
}
}
Not to say this is a better option, but I think it's nice to have a non-library-based option available.
querySelectorAll() documentation: https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

Categories