Fill a div only with JavaScript - javascript

I want to fill differents divs with four colours, using only javascript (with a HTML structure off course), here's the code :
HTML
<div id="content">
<div id="carre1" class="carre">1</div>
<div id="carre2" class="carre">2</div>
<div id="carre3" class="carre">3</div>
<div id="carre4" class="carre">4</div>
</div>
JS
var colors = {
count: 4,
tab : ["red","orange","yellow","green"]}
;
Let's say I want to make the div "carre1" red, how do I do that ?
Thanks in advance !

for (var i = 0; i < colors.tab.length; i++) {
document.getElementById("carre" + (i + 1)).style.backgroundColor= colors.tab[i];

In short:
for (var i=1; i<=colors['count']; i++) {
document.getElementById("carre" + i).style.backgroundColor = colors['tab'][i-1];
}
See this jsfiddle.
Also works with colors.tab and colors.count as in this jsfiddle.

This is how you fill div's with colors in order they are stored in array:
carre = document.getElementsByClassName('carre');
for(i=0;i<colors.count;i++){
carre[i].style.backgroundColor = colors.tab[i];
}

document.getElementById("carre1").style.backgroundColor=colors.tab[0];

Related

Javascript can't get content of element

I've written code using Javascript to format the following section of a webpage based on the values:
<div class="col-md-auto mx-auto">
<h3>Average price</h3>
<p id="avgPrice"></p>
<br>
<div>Average change</div>
<div class="change" id = "avgChange"></div>
</div>
<div class="col-md-auto mx-auto">
<h3>Max price</h3>
<p id="maxPrice"></p>
<br>
<div>Max change</div>
<div class="change" id="maxChange"></div>
</div>
(The values for the text within each of the id's are getting pulled from a database, and appear correctly on the webpage when I start the server)
Here is my Javascript to format the HTML based on positive/negative values:
function changeFormatter() {
var elements = document.getElementsByClassName("change");
for (var i = 0; i < elements.length; i++) {
var change = elements[i]; //this is where the problem is
console.log(change);
if (change > 0) {
elements[i].innerHTML = "▴ " + change + "%";
elements[i].classList.add("text-success");
}
if (change < 0) {
elements[i].innerHTML = "▾ " + change + "%";
elements[i].classList.add("text-danger");
}
}
}
This code is being called by the following eventlistener:
window.addEventListener('load', (event) => {
console.log('page is fully loaded');
getData(); //gets values from database and adds them to HMTL
changeFormatter();
});
The issue is the line where I'm defining the var change. The output of the console.log on the line below it shows the text I want is there, see image below:
But no matter what I try I cannot get the text contained within this div. I've tried elements[i].value, .textContent, .innerHTML, .innerText, parseFloat(elements[i].innerHTML)... but they all return 'undefined' when I try and log them. I would really appreciate any suggestions!
Output of console.log(elements[i], elements[i].innerHTML)
.innerHTML should be correct as seen here: https://jsfiddle.net/awLynp28/3/. All I did was copy your script, have it run on page load (since it looks like you have something like that in there, I am assuming your function is getting called after the data is fully called in), and change
var change = parseFloat(elements[i].innerHTML);
document.addEventListener('DOMContentLoaded', function() {
var elements = document.getElementsByClassName("change");
for (var i = 0; i < elements.length; i++) {
var change = parseFloat(elements[i].innerHTML); //this is where I put innerHTML
console.log(change);
if (change > 0) {
elements[i].innerHTML = "▴ " + change + "%";
elements[i].classList.add("text-success");
}
if (change < 0) {
elements[i].innerHTML = "▾ " + change + "%";
elements[i].classList.add("text-danger");
}
}
}, false);

Count divs that are hidden

I need a vanilla JS way to count the number of hidden divs on a page.
I have three divs with inline styles display: none. I thought this would work, but no luck:
var hiddenContainers = (document.getElementsByClassName(".emp-container").style.display == "none").length;
I have tried several solutions from SO and found a few JQuery ones that were successful, but what I'm writing needs to be done exclusively in regular old JavaScript.
EDIT: This works, but it seems like an unnecessarily roundabout way to get what I want:
var hiddenContainers = [];
var containers = document.querySelectorAll(".emp-container");
for (var i = 0; i < containers.length; i++) {
if (containers[i].style.display == "none") {
hiddenContainers.push(containers[i]);
}
}
function countclick(){
var m = document.querySelectorAll('.divs[style*="display:none;"]').length;
document.getElementById('count').innerHTML = "Hidden Divs: "+m;
}
<div class='divs' style="display:none;">a</div>
<div class='divs' style="">b</div>
<div class='divs' style="">c</div>
<div class='divs' style="display:none;">d</div>
<div class='divs' style="">e</div>
<div class='divs' style="display:none;">f</div>
<hr/>
<span id="count">Hidden Divs: 0</span><br/>
<button onclick='countclick();'>Count</button>

Append/Pass the array values from javascript to HTML Div?

var array = []; //In this i have 2 items
<div id="content"></div>
In this div id I need to pass the above array elements.
Ho can I do this?
Below is the basic example, how you interact with your DOM with javascript.
var array = [1, 2];
var content = document.getElementById("content");
for(var i=0; i< array.length;i++){
content.innerHTML += i + '--' + array[i] + '<br>';
}
<div id="content">
</div>
Big Note:
You can also use Javascript Templating if you are looking for passing a lot of other data as well to the View
You can use document.getElementById to get the id of the <div> and then insert the array as a string which will convert to the comma separated value:
var array = ['apple','ball']; //In this i have 2 items
document.getElementById('content').innerHTML = array.toString();
<div id="content"></div>
You Looking for Something like this ?
<div class="dummy" style="height: 100px;width: 100px;border: 1px solid black;"></div>
jQuery(document).ready(function(){
var arr = ['1','2'];
jQuery.each( arr, function( i, val ) {
jQuery('.dummy').append(val);
jQuery('.dummy').append("<br>");
});
});
jsfiddle : https://jsfiddle.net/vis143/c1kz0b8o/

How to get the text from a div which has children in it

I am currently studying JavaScript and I have the following problem. Is it possible to get only the text from a div which has children inside it? I managed to make it work only for the text which appears before the div's children.
PS: I would like to mention that I am trying to achieve this using only pure JavaScript.
var Class = document.querySelectorAll('div,b');
for (var i=0; i < Class.length; i++){
console.log(Class[i].childNodes[0].nodeValue);
}
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>
<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
It's not very clean way, but try something like this :
//get all div's with Bio css class (You can change it)
var Class = document.querySelectorAll('.Bio');
var sp=document.getElementById('res');
var arr=[]; //I put result into array so You can use it where You need
for (var i=0; i < Class.length; i++) {
for(var x=0;x<Class[i].childNodes.length;x++) {
if(Class[i].childNodes[x].nodeValue==null) {
//get value, innerHTML, from <b>
//res.innerHTML+=Class[i].childNodes[x].innerHTML+'<br>';
arr.push(Class[i].childNodes[x].innerHTML);
} else {
//get div innerHTML (before,after every child node
//res.innerHTML+=Class[i].childNodes[x].nodeValue+'<br>';
arr.push(Class[i].childNodes[x].nodeValue);
}
}
}
//show result into that span
for(var i=0;i<arr.length;i++) {
res.innerHTML+=arr[i]+'<br>';
}
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>
<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
<br><br>
<!-- I use this span to show result -->
<span id="res"></span>
var Class = document.querySelectorAll('div');
for (var i=0; i < Class.length; i++){
var children = [];
var boldText = Class[i].querySelectorAll('b')[0].innerText;
var otherText = Class[i].innerText.split(Class[i].querySelectorAll('b')[0].innerText)
children.push(otherText[0]);
children.push(boldText);
children.push(otherText[1]);
console.log(children);
}
Output :-
["My name is ", "John Doe", " and I am coming from Texas"]
["My name is ", "Jean Frye", " and I am coming from Alabama"]
This might do the trick.
You can use innerText to get only the text of your selected element.
var Class = document.querySelectorAll('div');
for (var i=0; i < Class.length; i++){
console.log(Class[i].innerText);
}
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>
<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
For more information, reference the MDN article on innerText

How to get child element by ID in JavaScript?

I have following html:
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
How can I get textarea element? I can't use document.getElementById("textid") for it
I'm doing it like this now:
var note = document.getElementById("note");
var notetext = note.querySelector('#textid');
but it doesn't work in IE(8)
How else I can do it? jQuery is ok
Thanks
If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.
$('#note').find('#textid');
You can also use jQuery selectors to basically achieve the same thing:
$('#note #textid');
Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.
On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.
Update 2020.03.10
It's a breeze to use native JS for this:
document.querySelector('#note #textid');
If you want to first find #note then #textid you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(
var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;
Here is a pure JavaScript solution (without jQuery)
var _Utils = function ()
{
this.findChildById = function (element, childID, isSearchInnerDescendant) // isSearchInnerDescendant <= true for search in inner childern
{
var retElement = null;
var lstChildren = isSearchInnerDescendant ? Utils.getAllDescendant(element) : element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].id == childID)
{
retElement = lstChildren[i];
break;
}
}
return retElement;
}
this.getAllDescendant = function (element, lstChildrenNodes)
{
lstChildrenNodes = lstChildrenNodes ? lstChildrenNodes : [];
var lstChildren = element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].nodeType == 1) // 1 is 'ELEMENT_NODE'
{
lstChildrenNodes.push(lstChildren[i]);
lstChildrenNodes = Utils.getAllDescendant(lstChildren[i], lstChildrenNodes);
}
}
return lstChildrenNodes;
}
}
var Utils = new _Utils;
Example of use:
var myDiv = document.createElement("div");
myDiv.innerHTML = "<table id='tableToolbar'>" +
"<tr>" +
"<td>" +
"<div id='divIdToSearch'>" +
"</div>" +
"</td>" +
"</tr>" +
"</table>";
var divToSearch = Utils.findChildById(myDiv, "divIdToSearch", true);
(Dwell in atom)
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
<script type="text/javascript">
var note = document.getElementById('textid').value;
alert(note);
</script>
Using jQuery
$('#note textarea');
or just
$('#textid');
$(selectedDOM).find();
function looking for all dom objects inside the selected DOM.
i.e.
<div id="mainDiv">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<div id="innerDiv">
link
<p>Paragraph 3</p>
</div>
</div>
here if you write;
$("#mainDiv").find("p");
you will get tree p elements together. On the other side,
$("#mainDiv").children("p");
Function searching in the just children DOMs of the selected DOM object. So, by this code you will get just paragraph 1 and paragraph 2. It is so beneficial to prevent browser doing unnecessary progress.

Categories

Resources