add (not replace) css class using javascript - javascript

I am using a ddsmoothmenu, and it is constructed in such a way that a class name can be dynamically added to the parent menu container via the plugin, and once the class is applied to the parent container, all css will also apply on the menu.
Here is how the ddsmoothmenu is passing classname:
<div id="myMenu">
<ul>
<li>.....</li>
</ul>
</div>
And the rendering of the menu is done by the following, where the 'classname' is being passed via the plugin to be added dynamically to the menu container.
ddsmoothmenu.init({
mainmenuid: 'myMenu',
orientation: 'h',
classname: 'ddsmoothmenu',
contentsource: 'markup'
});
So far so good. But I need to add a 'noindex' class to the menu container. I thought it's easy I will simply add in the markup, but the problem is the plugin replaces my class and add whatever is supplied from the above 'classname' parameter.
In the plugin itself: this line of code is the culprit:
$mainmenu.parent().get(0).className = setting.classname || "ddsmoothmenu"
where $mainmenu is basically the unordered list.
I know I can do a simple += to concatenate classnames. But I am not sure if that is possible in the above as it has the ternary if..else setup
Can I do $mainmenu.parent().get(0).className += setting.classname || "ddsmoothmenu"
I want something like the above line so that the class that I have hard coded in the markup gets to stay while the one added by the plugin simply gets appended to the class I have added directly in the markup?

All you have to do is take the current classname, add a space to it, and add the second classname. I understand you want to use a library but plain Javascript can do this easily:
function addclass(name,id) {
var element = document.getElementById(id); //not sure how you want to obtain your element
var currentclass = element.className;
element.className = currentclass + " " + name;
}
Again, not sure how you want to select document objects but as long as you add the space between class names, all should be good.

Here is a description from the jquery api doc on the addclass function:
Description: Adds the specified class(es) to each of the set of
matched elements.
version added: 1.0.addClass( className ) className Type: String One or
more space-separated classes to be added to the class attribute of
each matched element.
version added: 1.4.addClass( function ) function
Type: Function( Integer index, String currentClassName ) => String A
function returning one or more space-separated class names to be added
to the existing class name(s). Receives the index position of the
element in the set and the existing class name(s) as arguments. Within
the function, this refers to the current element in the set.
Below is an example use of jquery's addclass function that seems to do exactly what you're asking for.
$( "p" ).last().addClass( "selected" );
(ugh keep forgetting I can't post HTML)
Essentially it just tacks on the specified class to the selected element without removing any other classes.
Here is the link to the api doc

I like to use classie. it provides a stable way to add or remove classes to to DOM. The good thing is, it provides a fallback for Browsers without the classList function (e.g. IE8).
If your just looking for the Code Snippet:
addClass = function( elem, c ) {
elem.classList.add( c );
};
and
addClass = function( elem, c ) {
elem.className = elem.className + ' ' + c;
};

Related

jQuery adding new DOM elements having attributes within an element of specific id

Is there a methodToCreate in jQuery which could be written as
$("#someId").methodToCreate("tagName", ".className");
where an element with tag tagName would be added and given a class className and that too inside a specific element which would have an id someId?
$("<tag></tag>").addClass("className").attr({id: 'someId'}).appendTo( "body" )
Here's and example setting all the attributes individually.
As pointed out such function doesn't exist, but you could always create one .
(function( $ ){
$.fn.methodToCreate= function(tagName,className,id) {
$(id).append("<"+tagName+" "+"class="+"\'"+className+"\'>"+"SampleContent"+"</"+tagName+">");
return this;
};
})( jQuery );
and you can call this whenever you want in the following manner :
$(document).ready(function(){
$(document).methodToCreate('p','sampleClass','#someId');
});
Using this function(methodToCreate) you can dynamically pass the tagName , className and id of the element that you want to append to.
Here is the working fiddle : https://jsfiddle.net/varunsinghal65/udrxeg9m/1/#&togetherjs=TBEnLAnNzJ
Using jQuery you can create an element
var el = $('<tagName class="className"/>');
and then add it to a container
$('#someId').append(el);
$('#someId').append('<tagname class="className"></tagname>');
if you have the class stored in a variable (for example myClass) don't forget to quote it like this:
$('#someId').append('<tagname class="' + myClass + '"></tagname>');
No that method does not exist, but you can use .appendTo
like:
$("<tagName class='className'></tagName>").appendTo("#someId");
Hope it helps.

jquery hasClass, can it be given the beginning of class name, to get the full class name

I'm trying to do something similar to this question, but it's a bit different, so the solution there isn't working for me.
<span class="a-class another-class test-top-left"></span>
I have an element (this code shows a span but it could be div span or anything). This element has a class beginning with test- (test-top-left, test-top-right etc.) I've triggered a click event on classes starting with test- and saved the clicked object as var object = this;. Simple stuff so far.
What I'm trying to do now is get the full name of that class (test-top-left). I know it starts with test- but what's the full name. The thing is that there are other classes a-class another-class and test-top-left. Can hasClass be used to get the full name of the class? I'd prefer not to use find() or filter() just because there may be additional elements within that also have class="test-"
Edit:
The code I have now is, but it gives me ALL the classes. What I need is the single class beginning with test-.
var object = this;
$(object).attr('class');
So now I for loop through all the classes and test each one separately, which seems like a lot of unnecessary code. I'm hoping jQuery has a clever way to get the exact class that was clicked right away.
Description
You can use jQuerys Attribute Contains Selector, .attr() and .click() method.
Attribute Contains Selector - Selects elements that have the specified attribute with a value containing the a given substring.
.attr() - Get the value of an attribute for the first element in the set of matched elements.
.click() - Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
Sample
html
<span class="anyclass test-hello">Hello World</span>​
jQuery
$("[class*='test']").click(function() {
var object = $(this);
alert(object.attr("class").match(/(test-.*?)(?:\s+|$)/)[1])
;});
Check out the updated jsFiddle
Update
If you dont want to use regex you can do this.
$("[class*='test']").click(function() {
var object = $(this);
alert("test-" + object.attr("class").split("test-")[1].split("-"))
;});
​
More Information
jQuery - Attribute Contains Selector
jQuery - .attr()
jQuery - .click()
jsFiddle Demonstration
This should work for you:
var object = this;
var className = object.className.match(/(test-.*?)(?:\s+|$)/)[1];
Class name is the name of the class you are looking for.
If you don't want to use split or regex, you can try having the class in a separate attribute
<span class="someclass test-something" _rel="test-something">test<span>
or
<span class="someclass" _rel="test-something">test<span>
with the script
$("[_rel*='test-']").click(....
And to retrieve the attribute, use $(this).attr("_rel")

Get class name using jQuery

I want to get the class name using jQuery
And if it has an id
<div class="myclass"></div>
After getting the element as jQuery object via other means than its class, then
var className = $('#sidebar div:eq(14)').attr('class');
should do the trick. For the ID use .attr('id').
If you are inside an event handler or other jQuery method, where the element is the pure DOM node without wrapper, you can use:
this.className // for classes, and
this.id // for IDs
Both are standard DOM methods and well supported in all browsers.
It is better to use .hasClass() when you want to check if an element has a particular class. This is because when an element has multiple class it is not trivial to check.
Example:
<div id='test' class='main divhover'></div>
Where:
$('#test').attr('class'); // returns `main divhover`.
With .hasClass() we can test if the div has the class divhover.
$('#test').hasClass('divhover'); // returns true
$('#test').hasClass('main'); // returns true
Be Careful , Perhaps , you have a class and a subclass .
<div id='id' class='myclass mysubclass' >dfdfdfsdfds</div>
If you use previous solutions , you will have :
myclass mysubclass
So if you want to have the class selector, do the following :
var className = '.'+$('#id').attr('class').split(' ').join('.')
and you will have
.myclass.mysubclass
Now if you want to select all elements that have the same class such as div above :
var brothers=$('.'+$('#id').attr('class').split(' ').join('.'))
that means
var brothers=$('.myclass.mysubclass')
Update 2018
OR can be implemented with vanilla javascript in 2 lines:
const { classList } = document.querySelector('#id');
document.querySelectorAll(`.${Array.from(classList).join('.')}`);
This is to get the second class into multiple classes using into a element
var class_name = $('#videobuttonChange').attr('class').split(' ')[1];
you can simply use,
var className = $('#id').attr('class');
If your <div> has an id:
​<div id="test" class="my-custom-class"></div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
...you can try:
var yourClass = $("#test").prop("class");
If your <div> has only a class, you can try:
var yourClass = $(".my-custom-class").prop("class");
If you're going to use the split function to extract the class names, then you're going to have to compensate for potential formatting variations that could produce unexpected results. For example:
" myclass1 myclass2 ".split(' ').join(".")
produces
".myclass1..myclass2."
I think you're better off using a regular expression to match on set of allowable characters for class names. For example:
" myclass1 myclass2 ".match(/[\d\w-_]+/g);
produces
["myclass1", "myclass2"]
The regular expression is probably not complete, but hopefully you understand my point. This approach mitigates the possibility of poor formatting.
To complete Whitestock answer (which is the best I found) I did :
className = $(this).attr('class').match(/[\d\w-_]+/g);
className = '.' + className.join(' .');
So for " myclass1 myclass2 " the result will be '.myclass1 .myclass2'
<div id="elem" class="className"></div>
With Javascript
document.getElementById('elem').className;
With jQuery
$('#elem').attr('class');
OR
$('#elem').get(0).className;
You can get class Name by two ways :
var className = $('.myclass').attr('class');
OR
var className = $('.myclass').prop('class');
If you do not know the class name BUT you know the ID you can try this:
<div id="currentST" class="myclass"></div>
Then Call it using :
alert($('#currentST').attr('class'));
If you want to get classes of div and then want to check if any class exists then simple use.
if ( $('#div-id' ).hasClass( 'classname' ) ) {
// do something...
}
e.g;
if ( $('body').hasClass( 'home' ) ) {
$('#menu-item-4').addClass('active');
}
Try it
HTML
<div class="class_area-1">
area 1
</div>
<div class="class_area-2">
area 2
</div>
<div class="class_area-3">
area 3
</div>
jQuery
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="application/javascript">
$('div').click(function(){
alert($(this).attr('class'));
});
</script>
If we have a code:
<div id="myDiv" class="myClass myClass2"></div>
to take class name by using jQuery we could define and use a simple plugin method:
$.fn.class = function(){
return Array.prototype.slice.call( $(this)[0].classList );
}
or
$.fn.class = function(){
return $(this).prop('class');
}
The use of the method will be:
$('#myDiv').class();
We have to notice that it will return a list of classes unlike of native method element.className which returns only first class of the attached classes. Because often the element has more than one class attached to it, I recommend you not to use this native method but element.classlist or the method described above.
The first variant of it will return a list of classes as an array, the second as a string - class names separated by spaces:
// [myClass, myClass2]
// "myClass myClass2"
Another important notice is that both methods as well as jQuery method
$('div').prop('class');
return only class list of the first element caught by the jQuery object if we use a more common selector which points many other elements. In such a case we have to mark the element, we want to get his classes, by using some index, e.g.
$('div:eq(2)').prop('class');
It depends also what you need to do with these classes. If you want just to check for a class into the class list of the element with this id you should just use method "hasClass":
if($('#myDiv').hasClass('myClass')){
// do something
}
as mentioned in the comments above. But if you could need to take all classes as a selector, then use this code:
$.fn.classes = function(){
var o = $(this);
return o.prop('class')? [''].concat( o.prop('class').split(' ') ).join('.') : '';
}
var mySelector = $('#myDiv').classes();
The result will be:
// .myClass.myClass2
and you could get it to create dynamically a specific rewriting css rule for example.
Regards
This works too.
const $el = $(".myclass");
const className = $el[0].className;
if we have single or we want first div element we can use
$('div')[0].className otherwise we need an id of that element
Best way to get class name in javascript or jquery
attr() attribute function is used to get and set attribute.
Get Class
jQuery('your selector').attr('class'); // Return class
Check class exist or not
The hasClass() method checks if any of the selected elements have a specified class name.
if(jQuery('selector').hasClass('abc-class')){
// Yes Exist
}else{
// NOt exists
}
Set Class
jQuery('your selector').attr('class','myclass'); // It will add class to your selector
Get Class on Click of button using jQuery
jQuery(document).on('click','button',function(){
var myclass = jQuery('#selector').attr('class');
});
Add class if selector have no any class using jQuery
if ( $('#div-id' ).hasClass( 'classname' ) ) {
// Add your code
}
Get the second class into multiple classes using into a element
Change array position in place of [1] to get particular class.
var mysecondclass = $('#mydiv').attr('class').split(' ')[1];
Direct way
myid.className
console.log( myid.className )
<div id="myid" class="myclass"></div>
use like this:-
$(".myclass").css("color","red");
if you've used this class more than once then use each operator
$(".myclass").each(function (index, value) {
//do you code
}

how to append a css class to an element by javascript?

Suppose a HTML element's id is known, so the element can be refereced using:
document.getElementById(element_id);
Does a native Javascript function exist that can be used to append a CSS class to that element?
var element = document.getElementById(element_id);
element.className += " " + newClassName;
Voilà. This will work on pretty much every browser ever. The leading space is important, because the className property treats the css classes like a single string, which ought to match the class attribute on HTML elements (where multiple classes must be separated by spaces).
Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.
In prototype, for instance:
// Prototype automatically checks that the element doesn't already have the class
$(element_id).addClassName(newClassName);
See how much nicer that is?!
Adding class using element's classList property:
element.classList.add('my-class-name');
Removing:
element.classList.remove('my-class-name');
classList is a convenient alternative to accessing an element's list of classes.. see http://developer.mozilla.org/en-US/docs/Web/API/Element.classList.
Not supported in IE < 10
When an element already has a class name defined, its influence on the element is tied to its position in the string of class names.
Later classes override earlier ones, if there is a conflict.
Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.
document.addClass= function(el, css){
var tem, C= el.className.split(/\s+/), A=[];
while(C.length){
tem= C.shift();
if(tem && tem!= css) A[A.length]= tem;
}
A[A.length]= css;
return el.className= A.join(' ');
}
You should be able to set the className property of the element. You could do a += to append it.
addClass=(selector,classes)=>document.querySelector(selector).classList(...classes.split(' '));
This will add ONE class or MULTIPLE classes :
addClass('#myDiv','back-red'); // => Add "back-red" class to <div id="myDiv"/>
addClass('#myDiv','fa fa-car') //=>Add two classes to "div"
you could use setAttribute.
Example:
For adding one class:
document.getElementById('main').setAttribute("class","classOne");
For multiple classes:
document.getElementById('main').setAttribute("class", "classOne classTwo");

Looping through all select elements with JavaScript Prototype library

How can I (if it is possible) use the Prototype library to loop through all select elements on a page and access the element? In the documentation I found easily shortcuts for referencing elements with certain ids, class names etc. but no reference for elements with certain tag names.
If this is not possible with Prototype, an example with JQuery or another JS Library would be appreciated.
Check out the first example in this page:
$$('select').each(function() {
//
});
Essentially, the $$ function expects a CSS selector, and a tag name is a perfectly valid selector.
A jQuery example, for variety:
$('select').each(function() {
var selectedOption = $(this).find('option:selected');
alert('Value: ' + selectedOption.val() + ' Text: ' + selectedOption.text());
});
That will iterate over all selects in the page, and alert the text and value of the selected option on each select.

Categories

Resources