Change Multiple Classes with the same name using JavaScript? - javascript

Check out my small project on codepen below...
http://codepen.io/ajduff14/pen/DlHge
Basically I'm just testing out my JavaScript knowledge and I want to learn how to change all the buttons to the same class and use JavaScript to input a color that will change the background color of all the buttons with the given class "buttons". I can only manage to get it to work for 1 class at a time but not several.
It's probably a simple answer but I've done quite a bit of digging for it already and I can't find one! Could someone please help?
Thanks,
Adam

There is no way to change classes or styles on many elements at the same time, you'll have to iterate and apply it to one element at a time
var buttons = document.querySelectorAll('.buttons');
for (var i=0; i<buttons.length; i++) {
buttons[i].style.background = 'red';
buttons[i].className = buttons[i].className + ' newclass';
}

There were some trivial mistakes in your HTML and JS code.
1) In many places, instead of class="buttons" for input tag, you specified it as id="buttons". Remember that you should have a unique id for each element.
2) You were setting the style.backgroundColor property for buttons[3] and not for all objects with class name buttons.
document.getElementsByClassName('buttons') gets you an array of objects with class name "buttons." You need to iterate over every element of this array and set its background color property to appropriate value.
You could use a for-in loop or a standard for loop to achieve this purpose. I have used the for-in loop.
for (button in buttons) {
buttons[button].style.backgroundColor = div2.children[0].value;
}
See this link for a working copy of your project: http://jsfiddle.net/mayank_agarwal/LaQuz/

Related

hasClass not working. I try to add class to div when "active-card" class appears on it. any ideas?

I try to add class to div when "active-card" class appears on it. Tried different solutions, can't make that stuff work. Any ideas?
jQuery(document).ready(function($){
if ($(".card").hasClass("active-card")) {
$(".card").addClass("card-opacity");
}
});
First I will assume some things in my answer.
1 – there are multiple .card elements on your page
2 – you only want to add the class ‘card-opacity’ to a single element on dom
That being said you need to go through every card element and check if that specific element has the active-card class. In this case I used the map() function to iterate each element, but you can use your favorite loop function to iterate through an array.
// First get all '.card' elements and iterate through them
$('.card').map((card, index) => {
// check if the card element has the class 'active-card'
if($(card).hasClass('active-card')) {
// if true add the class 'card-opacity' to that element
$(card).addClass('card-opacity');
}
})
as #ikik commented try to explain your question and give as much information as possible, so it’s easier for everyone to help

How do I display a unique id value with GTM?

I have multiple elements on a page with the same class name, but each element has a unique id name.
Example:
<div class="video-image" id="get-googled">
<div class="video-image" id="email-marketing">
I want to display the id value, but right now I am only able to have GTM return and display the first element on the page. I read this post: "Getting value of ID from class" and it didn't help and even explains doing it the simple way will only display the first elements value.
Do I need custom Javascript to create this properly?
If you want to get a specific div and you know where it is on the page you might be able to use a DOM variable with an nth of type query selector. But this seems cumbersome, and since it seems you want a list in any case I think you are better of with a custom javascript variable:
function() {
return document.querySelectorAll(".video-image");
}
which return a collection of DOM elements (you might want to check if there are actually elements with that class first).
The initial answer is the right start - this completes the loop:
<script>
var inputs = document.querySelectorAll(".video-image");
for (var i = 0; i < inputs.length; i++) {
alert(inputs[i].id);
}
</script>
Here is a JSFiddle to try it out - [https://jsfiddle.net/JMurphy22/kduybmsp/2/][1]

Add Class to Array of ID's in Javascript

I am using .map to get an array of element IDs (this is named 'ids') that have a 'default-highlight' class. After removing that class on mouseenter, I want to return that class to those specific id's (basically, leave it how I found it).
Two things are causing me trouble right now:
When I dynamically add data-ids to the td elements and then use those data-ids to create the array of 'ids' my mouseenter stops adding the 'HIGHLIGHT' class (NO idea why this is happening)
On mouseleave I can't loop through the 'ids' and return the 'default-highlight' class to the elements they originally were on
I figure I should be using something like this, but it obviously isn't working:
$.each(ids, function() {
$(this).addClass('default-highlight');
});
I have tried a number of things, but keep coming up short. I am attaching a link to a codepen.io where I use data-ids that are being dynamically added to the table (this one the mouseenter doesn't work) and a codepen one where I am using regular IDs for the default highlight and everything appears to work like it is supposed to be (It isn't, since I want to be using the dynamically generated data-ids and then the subsequently produced array to reapply those classes).
Both of these codepens have a gif at top showing how the interaction should work.
If anything is unclear, please let me know. Thanks for reading!
You need to add # before id selector
$.each(ids, function() {
$('#'+this).addClass('default-highlight');
});
or you can use common selector by the help of map() and join()
$(ids.map(function(i, v) {
return '#' + v;
}).join()).addClass('default-highlight');
or you can add # when getting the id's and then you just need to join them
var ids = $('.default-highlight').map(function(i) {
return '#'+$(this).data('id');
}).get();
...
...
...
$(ids.join()).addClass('default-highlight');
It seems like storing the IDs and using those is overkill when you can store a reference to the jQuery element directly:
$highlightCells = $('.default-highlight').removeClass('default-highlight')
And later give the class back:
$highlightCells.addClass('default-highlight')
Here's a codepen fork: http://codepen.io/anon/pen/ZbOvZR?editors=101
Use this way:
$.each(ids, function() {
$("#" + this).addClass('default-highlight');
});

adding classes (serially numbered) to each DIV on page automatically via javascript?

i'm running a contact-form-plugin on my wordpress installation. everything works fine but i want to style my form a little bit more. to do it like this i have to style some DIVs (which the plugin is processing) in a different way. the problem is: all DIV-containers have no IDs or classes! everything is processed by the plugin and my PHP-skills are like zero so i have to deal with this "naked" DIVs ;-)
the question is: is it possible to add serially numbered classes to each DIV on the current site via javascript?
thanks so far and i hope you get waht i mean (sorry for that shitty english)!
Yet another way, passing a callback to .attr [docs]:
$('div').attr('class', function(i) {
return 'someClass' + i;
});
Though you could also use this for IDs instead, since each class will be unique.
Note that you don't have to use IDs or classes to select elements, there are a number of selectors and traversal methods with which you can get a reference to the elements you want.
To prevent overriding existing classes, either select only the elements with no class or somehow narrow down the selection of divs to only those you want:
$('div:not([class])')
or use .addClass [docs] instead of .attr:
$('div').addClass(function(i) {
return 'someClass' + i;
});
You need something like this,
Live Demo
$('div').each(function(i, item){
$(this).attr('class', "YourClass" + i); //You can replace i with some other variable if required and increment it.
});
You could do this:
var divs = document.getElementsByTagName("div");
var className = "myClass";
for( var i = 0, max = divs.length; i< max; i++ ){
divs[i].setAttribute("class",className + i.toString());
}

HTML - Accessing div in document exactly by position in one go

I have a page generated by Yii CListView which contains a div andmultiple child divs.I need to access a specific the child div and add one more div into that.
Although I managed to solve it using one approach but dont think its the right one. Following is the overview of my solution (the code below does not contain all necessary variables declarations and other stuff, I have pasted the core code not the complete.):
Accessed the parent div by Id (Since the Id was available as I can
code this into Yii)
Obtained all the elements in this div using :
var div_childern = document.getElementById('StudentGridViewId').getElementsByTagName('*');
Iterated through and when reached to the desired div, added my new div. Please note that the div in which I want to add new div has the class name as "items". Code as below:
for (var i = 0; i < div_childern.length; i++) {
if (div_childern[i].getAttribute('class')=='items'){
document.getElementById('StudentGridViewId').getElementsByTagName('*')[i].appendChild(newdiv);
i=div_childern.length+1;
}
}
The only problem in this solution is, I am accessing the whole document twice, the call to getElementsByTagName. First to obtain the list of all items and then again to add my new div. Is there a better way to this ?
and also, could anyone point me to set the Id of the "items" div that Yii generates?
Thanks
Faisal
You might be able to get a much more elegant solution if you use JQuery.
But, if you want to use the traditional javascript, here is what you could do
for (var i = 0; i < div_childern.length; i++) {
if (div_childern[i].getAttribute('class')=='items'){
div_childern[i].appendChild(newdiv);
i=div_childern.length+1;
}
}

Categories

Resources