How to remove .class1, .class2, ... or classN? - javascript

we have this classnames
.lightbox620
.lightbox400
..
.lightbox200
That we apply to the body page and it determines its width...
so i need to remove this class,
how can i $('body').removeClass('ligbox{any}') ???

If that's the only class that you set to <body>, then remove all the classes
$("body").removeClass();
// or
document.body.className = "";
If not, go the plain DOM way, use a regular expression to strip the class name out of the string.
document.body.className = document.body.className.replace(/\blightbox\d+/, "");
The jQuery way is a bit more complicated here:
$("body").removeClass(function (index, oldClass) {
var matches = oldClass.match(/\blightbox\d+/) || [];
return matches[0];
});

Related

Replace a style value in javascript

I am looking to change a value in a tag with js.
<div class="class1" style="background-image:url(https://www.awebsite.com/sites/default/files/a_image.jpg?t=1529620960)"></div>
I want to change this :
https://www.awebsite.com/sites/default/files/a_image.jpg?t=1529620960`
to this:
https://hello.com/an-other-image.jpg
Thanks !
You can use document.querySelector to get a reference to the <div> element and then update it's style attributes.
// querySelector can use CSS selectors to find the element in the document
// note: this is assuming there is only 1 element on page with this class
var myDiv = document.querySelector('.class1');
// Style properties generally match CSS but camel cased
myDiv.style.backgroundImage = 'url("https://hello.com/an-other-image.jpg")';
You may want to consider adding an id in which case you can use an ID selector or document.getElementById.
If there are multiple elements you want to update, you can use document.querySelectorAll which will return an array of matches which you can loop over and change.
function changeToAnotherBgImage(element) {
element.style.backgroundImage = 'url("https://hello.com/an-other-image.jpg")';
}
// Plenty of alternate ways of writing, arrow function may be appropriate
document.querySelectorAll('.class1').forEach(changeToAnotherBgImage);
You can do something like:
c = document.getElementsByClassName('class1');
for(i = 0; i < c.length; i++){
c[i].style.backgroundImage = 'url(https://hello.com/an-other-image.jpg)';
}
You can do that:
const eleDiv =document.querySelector('.class').style.background = "url('your imge') no-repeat";

Using JavaScript & jQuery in a single function (Nodes & Stuff)

I am currently learning jQuery. I know that jQuery is a custom library for JavaScript.
I am doing some learning examples in a book that is only using JavaScript, and to further my learning experience, I am trying to make use of jQuery for anything that might be more efficient.
So, I have this code:
function addLetter(foo) {
$(foo).unbind('click');
var tileLetter = $(foo).attr('class').split(' ');
var letter = tileLetter[2].charAt(1);
if (document.getElementById('currentWord').childNodes.length > 0) {
$('#currentWord p').append(letter);
} else {
var p = document.createElement('p');
var txt = document.createTextNode(letter);
p.appendChild(txt);
$('#currentWord').append(p);
}
}
Question #1:
If I change document.getElementById('currentWord').childNodes.length to $('#currentWord').childNodes.length it doesn't work. I thought the jQuery selector was the same thing as the JS document.getElementById as that it brought me back the DOM element. If that was the case, it'd make sense to be able to use the .childNodes.length functions on it; but it doesn't work. I guess it's not the same thing?
Question #2:
The code is textbook code. I have added all the jQuery that there is in it. My jQuery knowlede is limited, is there a more efficient way to execute the function?
The function's purpose:
This function is supposed to create a p element and fill it with a Text Node if it's the first time it's run. If the p element has already been created, it simply appends characters into it.
This is a word generating game, so you click on a letter and it gets added to a 'currentWord' div. The tile's letter is embedded in the 3rd css class, hence the attr splitting.
Thanks!
document.getElementById('currentWord')
returns a DOM object whereas $('#currentWord') returns a DOM object wrapped inside a jQuery object.
To get the plain DOM object you can do
$('#currentWord').get(0)
So
$('#currentWord').get(0).childNodes.length
should work.
Question #1:
jQuery returns a jQuery object. To return it to a regular javascript object use $(object)[0] and you can then treat it as a plain javascript (or DOM) object.
Question #2:
The efficiency looks good to me. Although you might want to use spans instead of p elements.
I guess one thing you could do (even though yours looks to run very fast) is cache the dom element:
function addLetter(foo) {
$(foo).unbind('click');
var tileLetter = $(foo).attr('class').split(' ');
var letter = tileLetter[2].charAt(1);
var currentWord = document.getElementById('currentWord');
if (currentWord.childNodes.length > 0) {
$(currentWord).find('p').append(letter);
} else {
var p = document.createElement('p');
p.innerHTML = letter;
currentWord.appendChild(p);
}
}
Calls to the jQuery() function ($()) return a jQuery object containing the matching elements, not the elements themselves.
Calling $('#some-id') will, then, return a jQuery object that contains the element that would be selected by doing document.getElementById('some-id'). In order to access that element directly, you can get it out of that jQuery object, using either the .get() function or an array index syntax: $('#some-id')[0] (it's 0-indexed).
I think you can replace all of this with a call to the text function.
function addLetter(foo) {
$(foo).unbind('click');
var tileLetter = $(foo).attr('class').split(' ');
var letter = tileLetter[2].charAt(1);
var currentWordP = $('#currentWord p');
if (currentWordP.size() > 0) {
currentWordP.text(currentWordP.text() + letter);
} else {
$('#currentWord').append("<p>" + letter + "</p>");
}
}
1: Use $.get(0) or $[0] to get the DOM element. e.x. $('#currentWord')[0].childNodes.length.
2: Try this:
function addLetter(foo) {
$(foo).unbind('click');
var tileLetter = $(foo).attr('class').split(' ');
var letter = tileLetter[2].charAt(1);
if ($('#currentWord p').length > 0) {
$('#currentWord p').append(letter);
} else {
$('#currentWord').append(
$('<p />', { text: letter })
);
}
}
Question #1:
document.getElementById returns DOM object. more
childNodes.length is property of Node object which is returned by document.getElementById.
jQuery selector returns jQuery object more. You can get DOM object from jQuery object using .get
$('#IDselector').get(0) = document.getElementById('IDselector')
Question #2:
function addLetter(foo) {
$(foo).unbind('click');
var tileLetter = $(foo).attr('class').split(' ');
var letter = tileLetter[2].charAt(1);
if ($('currentWord p').length > 0) {
$('#currentWord p').append(letter);
} else {
var p = $('<p />').text(letter);
$('#currentWord').append(p);
}
}

jQuery: Getting "secondary" class

I'm using jQuery to loop through some elements in a document. These elements are of type <tr> with class .input-row. Some of the elements can also have a secondary class (for example .input-area).
I use $(".input-row").each() to loop through the elements, but how can I determine if the $(this)-element has a "secondary" class and if so, get the name of this?
$(".input-row").each(function(){
$.each($(this).attr('class').split(/\s+/), function(i, v){
if(v !== 'input-row'){
alert(v);
}
});
});
You can get the list of all classes using attr, and you could simply get rid of the the class you used to select the elements:
$(".input-row").each(function() {
var allClasses = $(this).attr("class"),
otherClasses = allClasses.replace("input-row", "");
});
If the element has more than two classes, then you will be left with a list of the other classes. To separate them, you could split on the spaces.
You can get all the classes on the element and then remove the one you know exists('input-row'), then you will be left with any other classes on that element.
$('.input-row').each(function() {
var classes = $.trim($(this).attr('class').replace('input-row', ''));
if (classes.length > 1) {
alert(classes) // Names of all of the remaining classes
}
}
If you want to get them individually, you can do classes.split(' ') to get an array.
I prefer a declarative approach. You know which classes there can be, so write cases for them:
$(".input-row.input-area").each( /* ... */ );
$(".input-row.input-field").each( /* ... */ );
If you for some reason don't know the class name, you can extract it along the lines of:
$(".input-row").each(function () {
var myClasses = this.className.split(" ");
$.each(myClasses, function (i, className) {
if (className != 'input-row') {
alert(className);
}
});
});
I'd go for this
var otherClasses = $('.input-row').attr('class').split(' ');
otherClasses.splice($.inArray("input-row", otherClasses),1);
Simply doing this
var otherClasses = $('.input-row').attr('class').replace('input-row', '').split(' ');
Will give you an extra string in the array with an empty value in it, because of the space behind "input-row"
You could also do something like this to detect the number of classes:
var nc = $('#myId').attr('class').split(' ').length;
Then if nc is greater than 1:
$('#myID').attr('class').split(' ')[1]
should return the 'secondary' class
See a fiddle

Removing a class from an HTML element using JavaScript

I am attempting to remove a class from an html tag using JavaScript but I have no idea where to start. I have searched but to no avail. While I am decently fluent in jQuery, I am not in JavaScript and I need to use JavaScript in this instance Anything I have found thus far would need to be adjusted for my own use, which I have not been successful at. Hopefully someone can explain it in a fool-proof way.
The element the class is attached to is the "ul" tag. The class is named "nojavaScript" and is only applied to this single instance of the "ul" tag. While as I said the class is only used once in the page, the "ul" tag is used in other instances with different classes or ids.
If it would make it easier for the JavaScript, I can change the class to an id.
I hope I have given you enough to go on. I will include an example of the html code below.
<ul id="lines_list" class="nojavaScript"></ul>
As I mentioned, if it's easier to remove an id than a class, I can make the current id a class, and the current class an id. But essentially it's the "nojavaScript" that needs to be removed.
Thanks!
Here's a pure js solution:
var ulArr = document.getElementsByClassName('nojavaScript');
for (var i = 0; i < ulArr.length; i++) {
ulArr[i].className = ulArr[i].className.replace('nojavaScript','');
}
First you select all elements with the given class name, then iterate over the result and replace the given class in the className attribute with an empty string.
UPDATE:
Here's a more robust solution that turns the removal into a parameterized function and handles stripping extra whitespaces from the beginning, end, and middle of the className attribute.
function removeClass(elem, className) {
//declare some regexes to help us strip the extra whitespace
var trimLeft = /^\s+/,
trimRight = /\s+$/,
stripDouble = /\s+/g;
//remove the class, strip extra whitespace, and reassign className
elem.className = elem.className.replace(className, '').replace(trimLeft, '').replace(trimRight, '').replace(stripDouble, ' ');
}
//declare name of class to remove and get an array of elements with that class
var toRemove = 'nojavaScript',
elArr = document.getElementsByClassName(toRemove);
//iterate over elements and remove the class
for (var i = 0; i < elArr.length; i++) {
removeClass(elArr[i], toRemove);
}
Here's a live demo ->
try this:
document.getElementById("lines_list").className = "";
function removeCSSClass(element, className) {
var cssClass = ' ' + element.className + ' ';
var index = cssClass.indexOf(' ' + className + ' ');
if (index >= 0) {
var newClass = cssClass.substr(0, index) + ' ' + cssClass.substr(index + className.length + 1);
element.className = newClass;
}
}
UPDATE: code now works in all occassions
function removeClassFromElement(el,className){
var classes = el.getAttribute('class').split(/[ ]+/g);
var class = "";
for(var i in classes)
if(classes[i] != className)
class += classes[i] + " ";
el.setAttribute('class',class);
}
removeClassFromElement(document.getElementById('lines_list'),'nojavaScript');
Here's a non regex method that is considerate of multiple classes on an element.
function removeClass(element, cssClass) {
var classes = element.className.split(' ');
var j = classes.length;
while (j--) {
if (classes[j] === cssClass) {
classes.splice(j, 1);
}
}
element.className = classes.join(' ');
}
var lines_list = document.getElementById('lines_list');
removeClass(lines_list, 'nojavaScript');
It splits on spaces to isolate whole class names whereas doing a simple search for the class name string and replacing with nothing might eat part of a longer class name.
Class name modification should be done on the className property with a RegExp replace to avoid clobbering other classNames which should stay:
var ele = document.getElementById( 'lines_list' );
ele.className = ele.className.replace( /(?:^|\s)nojavaScript(?:\s|$)/gm, ' ' );
http://jsfiddle.net/JAAulde/nWzaZ/3/
(genercized class names: http://jsfiddle.net/JAAulde/nWzaZ/2/ )
Without this regex, you either wipe the entire className, or you overkill and possibly take out a portion of foonojavaScript as well (you know, if you had such an odd class :P ). While this might not really be likely, it's good practice for when you run into code that might not be as specific.
This solution allows you to have as many classes on the element as you want, as similar as you desire, without worry of how you format them other than as specified by the W3C. No maintenance issues :).
(The RegExp specifically looks for your class preceded by start of string or white-space, and followed by white-space or end of string)
(This assumes you already have a handle on how to get the element(s) from the DOM in the first place.)

Get class list for element with jQuery

Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element?
ex.
<div class="Lorem ipsum dolor_spec sit amet">Hello World!</div>
I will be looking for a "special" class as in "dolor_spec" above. I know that I could use hasClass() but the actual class name may not necessarily be known at the time.
You can use document.getElementById('divId').className.split(/\s+/); to get you an array of class names.
Then you can iterate and find the one you want.
var classList = document.getElementById('divId').className.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
if (classList[i] === 'someClass') {
//do something
}
}
jQuery does not really help you here...
var classList = $('#divId').attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item === 'someClass') {
//do something
}
});
Why has no one simply listed.
$(element).attr("class").split(/\s+/);
EDIT: Split on /\s+/ instead of ' ' to fix #MarkAmery's objection. (Thanks #YashaOlatoto.)
On supporting browsers, you can use DOM elements' classList property.
$(element)[0].classList
It is an array-like object listing all of the classes the element has.
If you need to support old browser versions that don't support the classList property, the linked MDN page also includes a shim for it - although even the shim won't work on Internet Explorer versions below IE 8.
Here is a jQuery plugin which will return an array of all the classes the matched element(s) have
;!(function ($) {
$.fn.classes = function (callback) {
var classes = [];
$.each(this, function (i, v) {
var splitClassName = v.className.split(/\s+/);
for (var j = 0; j < splitClassName.length; j++) {
var className = splitClassName[j];
if (-1 === classes.indexOf(className)) {
classes.push(className);
}
}
});
if ('function' === typeof callback) {
for (var i in classes) {
callback(classes[i]);
}
}
return classes;
};
})(jQuery);
Use it like
$('div').classes();
In your case returns
["Lorem", "ipsum", "dolor_spec", "sit", "amet"]
You can also pass a function to the method to be called on each class
$('div').classes(
function(c) {
// do something with each class
}
);
Here is a jsFiddle I set up to demonstrate and test http://jsfiddle.net/GD8Qn/8/
Minified Javascript
;!function(e){e.fn.classes=function(t){var n=[];e.each(this,function(e,t){var r=t.className.split(/\s+/);for(var i in r){var s=r[i];if(-1===n.indexOf(s)){n.push(s)}}});if("function"===typeof t){for(var r in n){t(n[r])}}return n}}(jQuery);
You should try this one:
$("selector").prop("classList")
It returns a list of all current classes of the element.
var classList = $(element).attr('class').split(/\s+/);
$(classList).each(function(index){
//do something
});
$('div').attr('class').split(' ').each(function(cls){ console.log(cls);})
Update:
As #Ryan Leonard pointed out correctly, my answer doesn't really fix the point I made my self... You need to both trim and remove double spaces with (for example) string.replace(/ +/g, " ").. Or you could split the el.className and then remove empty values with (for example) arr.filter(Boolean).
const classes = element.className.split(' ').filter(Boolean);
or more modern
const classes = element.classList;
Old:
With all the given answers, you should never forget to user .trim() (or $.trim())
Because classes gets added and removed, it can happen that there are multiple spaces between class string.. e.g. 'class1 class2 class3'..
This would turn into ['class1', 'class2','','','', 'class3']..
When you use trim, all multiple spaces get removed..
Might this can help you too. I have used this function to get classes of childern element..
function getClickClicked(){
var clickedElement=null;
var classes = null;<--- this is array
ELEMENT.on("click",function(e){//<-- where element can div,p span, or any id also a class
clickedElement = $(e.target);
classes = clickedElement.attr("class").split(" ");
for(var i = 0; i<classes.length;i++){
console.log(classes[i]);
}
e.preventDefault();
});
}
In your case you want doler_ipsum class u can do like this now calsses[2];.
Thanks for this - I was having a similar issue, as I'm trying to programatically relate objects will hierarchical class names, even though those names might not necessarily be known to my script.
In my script, I want an <a> tag to turn help text on/off by giving the <a> tag [some_class] plus the class of toggle, and then giving it's help text the class of [some_class]_toggle. This code is successfully finding the related elements using jQuery:
$("a.toggle").toggle(function(){toggleHelp($(this), false);}, function(){toggleHelp($(this), true);});
function toggleHelp(obj, mode){
var classList = obj.attr('class').split(/\s+/);
$.each( classList, function(index, item){
if (item.indexOf("_toggle") > 0) {
var targetClass = "." + item.replace("_toggle", "");
if(mode===false){$(targetClass).removeClass("off");}
else{$(targetClass).addClass("off");}
}
});
}
Try This. This will get you the names of all the classes from all the elements of document.
$(document).ready(function() {
var currentHtml="";
$('*').each(function() {
if ($(this).hasClass('') === false) {
var class_name = $(this).attr('class');
if (class_name.match(/\s/g)){
var newClasses= class_name.split(' ');
for (var i = 0; i <= newClasses.length - 1; i++) {
if (currentHtml.indexOf(newClasses[i]) <0) {
currentHtml += "."+newClasses[i]+"<br>{<br><br>}<br>"
}
}
}
else
{
if (currentHtml.indexOf(class_name) <0) {
currentHtml += "."+class_name+"<br>{<br><br>}<br>"
}
}
}
else
{
console.log("none");
}
});
$("#Test").html(currentHtml);
});
Here is the working example: https://jsfiddle.net/raju_sumit/2xu1ujoy/3/
For getting the list of classes applied to element we can use
$('#elementID').prop('classList')
For adding or removing any classes we can follow as below.
$('#elementID').prop('classList').add('yourClassName')
$('#elementID').prop('classList').remove('yourClassName')
And for simply checking if the class is present or not we can use hasClass
I had a similar issue, for an element of type image. I needed to check whether the element was of a certain class. First I tried with:
$('<img>').hasClass("nameOfMyClass");
but I got a nice "this function is not available for this element".
Then I inspected my element on the DOM explorer and I saw a very nice attribute that I could use: className. It contained the names of all the classes of my element separated by blank spaces.
$('img').className // it contains "class1 class2 class3"
Once you get this, just split the string as usual.
In my case this worked:
var listOfClassesOfMyElement= $('img').className.split(" ");
I am assuming this would work with other kinds of elements (besides img).
Hope it helps.
javascript provides a classList attribute for a node element in dom. Simply using
element.classList
will return a object of form
DOMTokenList {0: "class1", 1: "class2", 2: "class3", length: 3, item: function, contains: function, add: function, remove: function…}
The object has functions like contains, add, remove which you can use
A bit late, but using the extend() function lets you call "hasClass()" on any element, e.g.:
var hasClass = $('#divId').hasClass('someClass');
(function($) {
$.extend({
hasClass: new function(className) {
var classAttr = $J(this).attr('class');
if (classAttr != null && classAttr != undefined) {
var classList = classAttr.split(/\s+/);
for(var ix = 0, len = classList.length;ix < len;ix++) {
if (className === classList[ix]) {
return true;
}
}
}
return false;
}
}); })(jQuery);
The question is what Jquery is designed to do.
$('.dolor_spec').each(function(){ //do stuff
And why has no one given .find() as an answer?
$('div').find('.dolor_spec').each(function(){
..
});
There is also classList for non-IE browsers:
if element.classList.contains("dolor_spec") { //do stuff

Categories

Resources