Now I am using "Perfect Scroller" which is a custom scroll bar plugin.
I followed the Document to setup.Here
I use code like below and every was good.
var container = document.getElementById('container');
Ps.initialize(container);
However, I want to use it by "ClassName" not by "ID" because there are lots of areas.
I know I can use
var container = document.getElementsByClassName('selected_area')[0];
But this is only one element.
My question is how to do it by ClassName?
You can do in a loop:
var container = document.getElementsByClassName('selected_area');
for(var i in container) {
Ps.initialize(container[i]);
}
This iterates all containers and initialize it independently.
var container = document.getElementsByClassName('selected_area');
for(var i = 0; i < container.size; i++){
Ps.initialize(container[i]);
}
Although I haven't had a look at this plugin you are using, so I don't know if it should be initialised more than once. Hope this helps
you can also use:
var container = document.querySelectorAll('.selected_area');
furthermore you can transform it to an array(it's only necessary if you want to use standard array methods)
var contArr = [].slice.call(container)
in this case you can then use it with forEach
contArr.forEach(function(x){Ps.initialize(x)}
Related
I'm trying to get all classes from one element, then add them to another element created dynamically. I was originally stuck on how to do this, but as I was typing out this question, I worked out a solution. However, it seems a bit verbose. Is there a way to do this same thing more efficiently, i.e. with fewer lines of code?
let classes = this.nextElementSibling.classList; // get classes from target element
classes += ''; // convert classlist object to string
let class_array = classes.split(' '); // convert string to array
const my_div = document.createElement('div'); // create a new div
for(i=0; i<class_array.length; i++) { // loop through array and add classes to the div
my_div.classList.add(class_array[i]);
}
Thanks in advance.
The className will give you a space-separated string of class names an element has. Just use that.
const my_div = document.createElement('div');
my_div.className = this.nextElementSibling.className;
I am trying to transition from pure JavaScript to jQuery. I have a for loop that dynamically creates HTML elements with data from an API. Here is my old code:
recipeDiv = [];
recipeDiv[i] = document.createElement("div");
recipeDiv[i].setAttribute("class", "recipeBlock");
recipeDiv[i].appendChild(someElement);
However, when I transitioned to jQuery and used this instead
recipeDiv = [];
recipeDiv[i] = $("<div/>").addClass("recipeBlock");
recipeDiv[i].appendChild(someElement);
I get the following error: recipeDiv[i].appendChild is not a function
I know that .appendChild() isn't jQuery (JS), but shouldn't it still work? Even if I use the jQuery .append() function, I still get an error.
Any help is greatly appreciated.
You seem to be confusing yourself by inter-changing jQuery and DOM APIs. They cannot be used interchangeably. document.createElement returns an Element and $("<div />") returns the jQuery object. Element object has the appendChild method and jQuery object has the append method.
As a good practice, I would suggest you choose between DOM APIs or jQuery, and stick to it. Here is a pure jQuery based solution to your problem
var recipeContainer = $("<div/>")
.addClass("recipeContainer")
.appendTo("body");
var recipeDiv = [];
var likes = [];
for (var i = 0; i < 20; i++) {
//Create divs so you get a div for each recipe
recipeDiv[i] = $("<div/>").addClass("recipeBlock");
//Create divs to contain number of likes
likes[i] = $("<div/>")
.addClass("likes")
.html("<b>Likes</b>");
//Append likes blocks to recipe blocks
recipeDiv[i].append(likes[i]);
//Append recipe blocks to container
recipeContainer.append(recipeDiv[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Maybe someElement is not created? Does the code need to be as follows?
recipeDiv = [];
var someElement = $("<div/>").addClass("recipeBlock");
recipeDiv[i].appendChild(someElement);
I have this code
<div class="g-popupgrid-item g-zoom" data-size="395x385">
I want to populate the 395x385 dynamically with the image size.
I have a JS function which gets the image size, I don't know how to print/echo/document.write it to be within the HTML tag.
I would avoid using jQuery for such a trivial task unless you are already using it in your project. Plain javascript:
var div = document.querySelector('.g-popupgrid-item');
var newSize = '100x100'; // for example
div.setAttribue('data-size', newSize);
Get the Node using JavaScript, then modify it to fit your needs:
var container = document.querySelector(".g-popupgrid-item .g-zoom")
container.setAttribute("data-size", value)
Keep in mind this will only affect the first element with those classes, if you want affect them all, use the code below:
var containers = document.querySelectorAll(".g-popupgrid-item .g-zoom")
containers.forEach(function(container) {
container.setAttribute("data-size", value)
})
Also keep in mind that containers is not an Array it's a NodeList. Read more here
EDIT: According to #Eoin, the .forEach() method on NodeLists is not supported in Firefox. You can also use a standard for loop in place of it:
var containers = document.querySelectorAll(".g-popupgrid-item .g-zoom")
for (var i = 0; i < containers.length; i++) {
containers[i].setAttribute("data-size", value)
}
So lets say I want to hide a div or span with CSS of a particular class.
Is there anyway to do so for the first X number of instances, or better yet, do it for all except for the last one? I imagine this would require javascript.
pseudocode I am thinking would look like this
if divname.class = "XYZ" {
select all instances -1
execute code that inserts random programmatic id into each class
execute code that hides all ids except the last one
}
Am I on the right track? Or is there any easier/better way?
If you can use jQuery and its nice pseudo-selectors, you could do something like
$('.question-summary:not(:last)')
You can test on the SO homepage.
You could do something like this,
var class_div = document.getElementsByClassName("class_name");
var i =0;
for(i=0;i<class_div.length-1;i++){
//do whatever you want with class_div[n-1] elements.
}
I am not sure how you do this with jquery but this is one possible solution for javascript.
If you were using jQuery...
$('.class_name').hide().last().show();
Here ya go - http://jsfiddle.net/uUK6G/
Set all your divs to the same class. Then use jQuery to filter out the last one.
$('.myDiv').filter(':not(:last)').hide();
You can use the :last-child selector in CSS to do this.
http://www.w3schools.com/cssref/sel_last-child.asp
Is there anyway to do so for the first X number of instances, or
better yet, do it for all except for the last one? I imagine this
would require javascript.
You can try:
var elms = document.getElementsByClassName('XYZ'), total = elms.length;
for (var i = 0; i < total; i++){
elms[i].style.display = 'none';
}
In above loop, i will contain index of each element, you can put condition or rather range to specify which ones to delete. For example, if you wanted to hide all except for last one, you would modify it like:
for (var i = 0; i < total - 1; i++){
elms[i].style.display = 'none';
}
Instead of individually calling $("#item").removeClass() for every single class an element might have, is there a single function which can be called which removes all CSS classes from the given element?
Both jQuery and raw JavaScript will work.
$("#item").removeClass();
Calling removeClass with no parameters will remove all of the item's classes.
You can also use (but it is not necessarily recommended. The correct way is the one above):
$("#item").removeAttr('class');
$("#item").attr('class', '');
$('#item')[0].className = '';
If you didn't have jQuery, then this would be pretty much your only option:
document.getElementById('item').className = '';
Hang on, doesn't removeClass() default to removing all classes if nothing specific is specified? So
$("#item").removeClass();
will do it on its own...
Just set the className attribute of the real DOM element to '' (nothing).
$('#item')[0].className = ''; // the real DOM element is at [0]
Other people have said that just calling removeClass works - I tested this with the Google jQuery Playground: http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGIS61gEM ... and it works. So you can also do it this way:
$("#item").removeClass();
Of course.
$('#item')[0].className = '';
// or
document.getElementById('item').className = '';
Remove specific classes:
$('.class').removeClass('class');
Say if element has class="class another-class".
The shortest method
$('#item').removeAttr('class').attr('class', '');
You can just try:
$(document).ready(function() {
$('body').find('#item').removeClass();
});
If you have to access that element without a class name, for example you have to add a new class name, you can do this:
$(document).ready(function() {
$('body').find('#item').removeClass().addClass('class-name');
});
I use that function in my project to remove and add classes in an HTML builder.
I like using native JavaScript to do this, believe it or not!
solution 1: className
Remove all class of all items
const items = document.querySelectorAll('item');
for (let i = 0; i < items.length; i++) {
items[i].className = '';
}
Only remove all class of the first item
const item1 = document.querySelector('item');
item1.className = '';
solution 2: classList
// remove all class of all items
const items = [...document.querySelectorAll('.item')];
for (const item of items) {
item.classList.value = '';
}
// remove all class of the first item
const items = [...document.querySelectorAll('.item')];
for (const [i, item] of items.entries()) {
if(i === 0) {
item.classList.value = '';
}
}
// or
const item = document.querySelector('.item');
item.classList.value = '';
jQuery ways (not recommended)
$("#item").removeClass();
$("#item").removeClass("class1 ... classn");
refs
https://developer.mozilla.org/en-US/docs/Web/API/Element/className
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
$('#elm').removeAttr('class');
Attribute "class" will no longer be present in "elm".
Since not all versions of jQuery are created equal, you may run into the same issue I did, which means calling $("#item").removeClass(); does not actually remove the class (probably a bug).
A more reliable method is to simply use raw JavaScript and remove the class attribute altogether.
document.getElementById("item").removeAttribute("class");
Let's use this example. Maybe you want the user of your website to know a field is valid or it needs attention by changing the background color of the field. If the user hits reset then your code should only reset the fields that have data and not bother to loop through every other field on your page.
This jQuery filter will remove the class "highlightCriteria" only for
the input or select fields that have this class.
$form.find('input,select').filter(function () {
if((!!this.value) && (!!this.name)) {
$("#"+this.id).removeClass("highlightCriteria");
}
});
Try with removeClass.
For instance:
var nameClass=document.getElementsByClassName("clase1");
console.log("after", nameClass[0]);
$(".clase1").removeClass();
var nameClass=document.getElementsByClassName("clase1");
console.log("before", nameClass[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clase1">I am a Div with class="clase1"</div>
I had a similar issue. In my case, on disabled elements was applied that aspNetDisabled class and all disabled controls had wrong colors. So, I used jQuery to remove this class on every element/control I want and everything works and looks great now.
This is my code for removing aspNetDisabled class:
$(document).ready(function () {
$("span").removeClass("aspNetDisabled");
$("select").removeClass("aspNetDisabled");
$("input").removeClass("aspNetDisabled");
});