If data attribute above X number add class to element - javascript

I need to add Class highpc to each element with the data attribute of procent, which is bigger than 51. I've got a jQuery solution, but I need it in pure JavaScript. Can anyone help me? This is what I got so far:
HTML
<span data-procent="4" class="procent">4%</span>
<span data-procent="59" class="procent">59%</span>
JS
function highpc(){
var procent = this.elem.getAttribute("data-procent");
if (parseInt(procent) > 51) {
procent.className=procent.className+" highpc";
}
}
window.onload = highpc();
http://jsfiddle.net/Zc8vY/1/

You haven't specified what is this.elem, and you haven't loop in your script.
You are also using variable procent for getting the data-attribute from your element. Later, you are trying to use it for linking the element. Try updated code:
function highpc(){
var elements = document.getElementsByClassName('procent');
for(i=0;i<elements.length;i++) {
var procent = elements[i].getAttribute("data-procent");
if (parseInt(procent) > 51) {
elements[i].className=elements[i].className+" highpc";
}
}
}
Updated fiddle http://jsfiddle.net/Zc8vY/4/

This is your fixed function:
function highpc() {
var elements = document.querySelectorAll('.procent');
for (var i = 0; i < elements.length; i++) {
var procent = elements[i].getAttribute("data-procent");
if (parseInt(procent) > 51) {
elements[i].className += " highpc";
}
}
}
window.onload = highpc;
Note the last line: you don't need () after highpc because you want window.onload to be a reference to a function, not a result of execution.
References: querySelectorAll to select elements.
Demo: http://jsfiddle.net/Zc8vY/3/

Using pure javascript and implementing own getElementsByClassName.
function getElementsByClass(className){
var celems = new Array();
var elems = document.getElementsByTagName("*");
for(var i = 0; i < elems.length;i++){
if(elems[i].className.indexOf(className) != -1){
celems.push(elems[i]);
}
}
return celems;
}
function highpc(){
var elems = getElementsByClass("procent");
console.log(elems);
for(var i = 0; i < elems.length; i++){
highpc_ex(elems[i]);
}
}
function highpc_ex(elem){
var procent = elem.getAttribute("data-procent");
if (parseInt(procent) > 51) {
elem.className=elem.className+" highpc";
}
}
window.onload = highpc();

WORKING FIDDLE HERE
function highpc() {
var aSpans = document.getElementsByTagName("span");
for(var i = 0; i < aSpans.length; i++) {
var eSpan = aSpans[i];
var procent = eSpan.getAttribute("data-procent");
if (procent != null && parseInt(procent) > 51) {
eSpan.className += " highpc";
}
}
}
This is a similar variant to what others have already posted. You might find this one to be more performant for larger sets of html.
Ref: Why .getElementsByTagName() is faster than .querySelectorAll()

Related

How to Change Color of Div within a for statement?

Inside my php while loop I output a div with id divborder, and class div-border
Inside that div i have another div with id title
<div id='divborder' class='div-border'>
<div id='Title'>This is Title</div> <br/> video elements
</div>
I have a JavaScript function that get called when the video ends
for (var i = 0; i < videos.length; i++) {
videos[i].addEventListener("ended", function(event)
{
var divBoader2 = document.getElementsByClassName("divborder")[3];
divBoader2.style.borderColor = "#b1ff99";
}
My Question is how do i change the border color of the div and the title of second div?
I can do it like this:
var divBoader2 = document.getElementsByClassName("divborder")[3];
divBoader2.style.borderColor = "#b1ff99";
which works but its not dynamic
Save the value of value at i in another variable declared with let
for (var i = 0; i < videos.length; i++) {
let index = i; //save the value as let so that its binding stays
videos[i].addEventListener("ended", function(event)
{
var divBoader = document.querySelectorAll("div-border")[index];
divBoader.style.borderColor = "#b1ff99";
}
}
Or if the video elements are within the div-border, then use closest
for (var i = 0; i < videos.length; i++) {
videos[i].addEventListener("ended", function(event)
{
var divBoader = event.currentTarget.closest(".div-border");
divBoader.style.borderColor = "#b1ff99";
}
}
A little less verbose code
[...videos].forEach( s => s.closest( ".div-border" ).style.color = "#b1ff99" )
Try this,
Give class name div-border instead of divborder
for (var i = 0; i < videos.length; i++) {
videos[i].addEventListener("ended", function(event)
{
var divBoader2 = document.getElementsByClassName("div-border")[3];
divBoader2.style.borderColor = "#b1ff99";
}
What you need is probably a videos[i].parentNode instead of document.getElementsByClassName("div-border")[3] (see https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode)

javascript dynamically adding and removing classes [duplicate]

This question already has answers here:
How can I change an element's class with JavaScript?
(33 answers)
Closed 5 years ago.
I am working on a simple example, if a user clicks on element then all the elements above it should have a class and all elements below it should not have any class applied to them.
Here is my code:
<script>
function test(object) {
var pid = object.id;
var id = parseInt(pid.split("")[1]);
console.log(id);
for (var i = 1; i <= id; i++) {
var element = document.getElementById("p"+i);
console.log(element);
element.className = "active";
}
console.log(id+1);
for(var i = id+1; i <= 4; i++) {
var element = document.getElementById("p"+i);
element.className.replace(new RegExp('(?:^|\\s)'+ 'active' + '(?:\\s|$)'), ' ');
console.log(element);
}
}
</script>
<div id="divid">
<p id="p1" onclick="test(this)">one</p>
<p id="p2" onclick="test(this)">two</p>
<p id="p3" onclick="test(this)">three</p>
<p id="p4" onclick="test(this)">four</p>
</div>
So here if I click on three then the elements for one, two, three should have the class active and element four should not have any class. This is working fine.
Now if I click on one, I am expecting that two, three, four should have any css class but it is not working like that.
Can you please help me where is the issue. I want to use plain Javascript.
It might be wise to consider an alternative to using the onclick attribute due to separation of concerns. The following allows you to alter the HTML without having to consider JavaScript while you work.
https://jsfiddle.net/gseh0wxc/2/
var getList = (selector) => [].slice.call(document.querySelectorAll(selector));
var paragraphs = getList("#divid p[id ^= 'p']");
paragraphs.forEach((paragraph, index) => {
paragraph.addEventListener('click', (e) => {
for (let i = 0; i < index; i++) {
paragraphs[i].classList.remove('active');
}
for (let i = index; i < paragraphs.length; i++) {
paragraphs[i].classList.add('active');
}
});
})
Please try this code
function test(object) {
var pid = object.id;
var id = parseInt(pid.split("")[1]);
console.log(id);
for (var i = 1; i <= id; i++) {
var element = document.getElementById("p"+i);
element.classList.add("active");
}
console.log(id+1);
for(var i = id+1; i <= 4; i++) {
var element = document.getElementById("p"+i);
element.classList.remove("active");
}
}
Hope this helps.
try this simple approach instead, don't need to extract id number and all, and with a single simple loop.
function test(option) {
//this will select all p tags id starts with "p" inside div having id "divid" and return a array
var targetPTags = document.querySelectorAll("div#divid p[id^=p]")
var idx, flag=false;
//we are iterating over that array and taking each dom element in el
for(idx=0;idx<targetPTags.length;idx++) {
var el = targetPTags[idx];
if(flag) {
//do operation you want for after elements in el
} else if(option===el) {
flag=true; // we are making flag true when its the element that clicked and doing no operation
//do the operation you want for the element, may be the same as below operation in else
} else {
//do operation you want for before element in el
}
}
}
Kind of similar to "Chatterjee"'s solution, but here you go:
function test(object)
{
var parentElem = null;
var childElems = null;
var currElemSet = false;
var i=-1;
try
{
parentElem = object.parentElement;
if(parentElem!=null)
{
childElems=parentElem.getElementsByTagName(object.nodeName); // could refine to accommodate sibling nodes only
if(childElems!=null)
{
for(i=0;i<childElems.length; i++)
{
if(currElemSet) childElems[i].className = "";
else childElems[i].className = "active";
if(childElems[i]==object) currElemSet = true;
}
}
}
}
catch(e)
{
alert("Error: " + e.Message);
}
finally
{
}
}

What is the plain Javascript equivalent of .each and $(this) when used together like in this example?

What is the plain Javascript equivalent of .each and $(this).find when used together in this example?
$(document).ready(function(){
$('.rows').each(function(){
var textfield = $(this).find(".textfield");
var colorbox = $(this).find(".box");
function colorchange() {
if (textfield.val() <100 || textfield.val() == null) {
colorbox.css("background-color","red");
colorbox.html("Too Low");
}
else if (textfield.val() >300) {
colorbox.css("background-color","red");
colorbox.html("Too High");
}
else {
colorbox.css("background-color","green");
colorbox.html("Just Right");
}
}
textfield.keyup(colorchange);
}
)});
Here's a fiddle with basically what I'm trying to accomplish, I know I need to use a loop I'm just not sure exactly how to set it up. I don't want to use jquery just for this simple functionality if I don't have to
http://jsfiddle.net/8u5dj/
I deleted the code I already tried because it changed every instance of the colorbox so I'm not sure what I did wrong.
This is how to do what you want in plain javascript:
http://jsfiddle.net/johnboker/6A5WS/4/
var rows = document.getElementsByClassName('rows');
for(var i = 0; i < rows.length; i++)
{
var textfield = rows[i].getElementsByClassName('textfield')[0];
var colorbox = rows[i].getElementsByClassName('box')[0];
var colorchange = function(tf, cb)
{
return function()
{
if (tf.value < 100 || tf.value == null)
{
cb.style.backgroundColor = 'red';
cb.innerText = "Too Low";
}
else if (tf.value > 300)
{
cb.style.backgroundColor = 'red';
cb.innerText = "Too High";
}
else
{
cb.style.backgroundColor = 'green';
cb.innerText = "Just Right";
}
};
}(textfield, colorbox);
textfield.onkeyup = colorchange;
}
var rows = document.querySelectorAll('.rows');
for (var i=0; i<rows.length; i++) {
var row = rows[i];
var textfield = row.querySelector('.textfield');
var colorbox = row.querySelector('.box');
// ...
}
Note that you must use a for loop to iterate the rows because querySelectorAll() does not return an array, despite appearances. In particular, that means that .forEach() isn't valid on the returned list.

JS: getElementByID wildcard

I have a table and a button.
If i click the button, all <tr> which have an id starting with "tr" (in the example the first 3) should be set to display = "none";
Here is a Fiddle
Has anyone a Idea how i get this to work?
Give all the elements that have id="tr_NNNN" a distinct class, e.g. class="tr tr_NNNN". Then use the following loop:
var hide_trs = document.getElementsByClassName('tr_NNNN');
for (var i = 0; i < hide_trs.length; i++) {
hide_trs[i].style.display = "none";
}
You can simply iterate through your tr elements using the IDs:
function doJS() {
for(var i = 1; i <= 3; i ++) {
document.getElementById("tr_" + i).style.display="none";
}
}
You can't supply a wildcard to gEBI, but you can use the attribute starts with selector in qSA:
document.querySelectorAll("[id^='tr_']")[0].style.display="none";
I agree with using classes instead of IDs for this, but this should satisfy your original question:
function doJS() {
var rows = document.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if(row.getAttribute("id") && /^tr/.test(row.getAttribute("id"))){
row.style.display = 'none';
}
}
}
http://jsfiddle.net/eHSwJ/14/
And while this isn't a jQuery question, I would point out that by leveraging jQuery, this can be reduced to:
$('tr[id^="tr"]').css('display', 'none');

for loop an argument in function

I was doing this code but it will take time because it will be h1 up until h24 so i decided to use a for loop but i don't know how..
this is my original code
function hover(h1,h2,h3,h4){
document.getElementById(h1).style.backgroundColor="orange";
document.getElementById(h2).style.backgroundColor="orange";
document.getElementById(h3).style.backgroundColor="orange";
document.getElementById(h4).style.backgroundColor="orange";
}
and i want to replace it something like this
function hover(
for(i = 1; i<=24; i++) {
document.write("h"+i+",");
}
)
but there is an error.. Please help me out.. Thank you
function hover() {
for(var i = 1; i < 25; i++) {
document.getElementById("h" + i).style.backgroundColor="orange";
}
}
If you could need more control, you could set the upper limit as a parameter, e.g.
function hover(limit) {
for(var i = 1; i <= limit; i++) {
document.getElementById("h" + i).style.backgroundColor="orange";
}
}
A call to hover(10); would change the background colour of h1 through h10.
There are several things wrong with the code you posted. I think I understand the problem you are trying to solve though. Try something like this:
function hover(eleId){
document.getElementById(eleId).style.backgroundColor="orange";
}
for(i=1; i<=24; i++){
hover("h"+i.toString());
}
Also note h1, h2, h3 all look like HTML tags. Check out getElementsByTagName.
You need to use Javascript's arguments object
function hover() {
var args = Array.prototype.slice.call(arguments);
var length = args.length;
for (var i = 0; i < length; i++) {
document.getElementById(args[i]).onmouseover =
function () { this.style.backgroundColor = "orange"; }
document.getElementById(args[i]).onmouseout =
function () { this.style.backgroundColor = "transparent"; }
}
}
jsFiddle Demo
HTML:
<div id="h1">A</div>
<div id="Hello">B</div>
<div id="box">C</div>
<div id="World">D</div>
JS Call:
hover("h1", "Hello", "box", "World");
Here is my suggestion :
<div id="h1">test</div>
<div id="h2">test</div>
<div id="h3">test</div>
<div id="h4">test</div>
script, notice the dummy variable
<script>
function hover(dummy){
for (var i=0; i<arguments.length; i++) {
var element = document.getElementById(arguments[i]);
element.onmouseover = function() {
this.style.backgroundColor="orange";
}
element.onmouseout = function() {
this.style.backgroundColor="white";
}
}
}
//hover('h1','h2','h3','h4');
for (var i=1;i<=24;i++) {
hover('h'+i);
}
</script>

Categories

Resources