I have several CSS classes in the form of a selector, for example .myclass.myclass2 and I want to apply both classes to an element.
I could .split() the string and apply each class with .addClass(), but before I do, I'd like to know if there's a "native" jQuery function to do this kind of thing or if someone has written a function to handle it.
To better explain: I want a function that I can pass it a CSS selector and it'll add the classes to an element. Like $('#myelem').addClass('.myclass.myclass').
(I would also love it to handle other CSS selectors such as #myid, but I fear that's asking too much and I'd probably need a full parser function.)
addClass takes a space separated string, so all you need to do is replace dots with spaces:
var classes = '.myclass.myclass2';
$(element).addClass(classes.replace(/\./g,' ').trim()))
You can add this to your script:
$.fn.oldAddClass = $.fn.addClass;
$.fn.addClass = function(x){
if(typeof x == 'string'){
this.oldAddClass(x.replace(/\./g, ' '));
}else{
this.oldAddClass(x);
}
}
Then call addClass() with your dot :
$(el).addClass('.class1.class2');
Fiddle : http://jsfiddle.net/8hBDr/
create two classes inside style tag like this
.a {
backgroud-color:red;
}
.b{
color:blue;
}
</style>
now add your jquery codes
then inside javascript code
<script type="text/javascript">
$(document).ready(function(){
$('#mydiv').addClass(a).addCLass(b);
or
$("#mydiv").addClass({a,b});
or
$('#mydiv').addClass(a);
$('#mydiv').addClass(b);
});
</script>
here is the html
<html>
<body>
<div id="mydiv"></div>
</body>
</html>
You cannot add css selectors (like #elemid.myclass) directly to an element in native jQuery. The example below shows how to add multiple classes using a space delimited string.
$(elem).addClass("myclass mycalss2")
And the documentation:
http://api.jquery.com/addClass/
Related
I'm trying to select the class p100 and replace it with a number that will be inputted by the user, does anyone know how to keep the "p" and replace the number in the class using jQuery?
<div class="c100 p100 small green storyline">
something like this can be done: $('.p100').removeClass('p100').addClass('p'+uservalue);
edit:
if you have more that one div with class p100:
$('.p100').each(function(){
$(this).removeClass('p100').addClass('p'+uservalue);
})
var item = $('.p100');
$('#button').click(() => {
item.removeClass('p100');
item.addClass('p200')
})
Working JSFiddle with visuals
You can set the class by using .attr(), like this:
$("#td_id").attr('class', 'newClass');
If you want to add a class, use .addclass() instead, like this:
$("#td_id").addClass('newClass');
Or a short way to swap classes using .toggleClass():
$("#td_id").toggleClass('change_me newClass');
Read more about Class attributes
While the other answers mention good ways with jquery, I'd like to add a vanilla javascript solution :) :
for(let elem of document.getElementsByClassName('p100'){
elem.classList.remove('p100');
elem.classList.add('p'+uservalue);
}
If you want to restrict it to divs (the above code will match every element with class p100) just replace document.getElementsByClassName('p100') with document.querySelectorAll('div .p100') :).
We could replace the two calls of .remove and .add with one call of .replace like this : elem.classList.replace('p100','p'+uservalue), Currently this function isn't implemented in all browsers.
Pay attention that classList is supported in IE10+, if you need IE9 support you need a polyfill, MDN already gives one and the polyfill provides replace function above too, see here : https://developer.mozilla.org/en-US/docs/Web/API/Element/classList (scroll down to see the polyfill)
for document.querySelectorAll support, it's supported in IE8(CSS2 selectors only) and IE9+(all CSS selectors including CSS3 ones).
Using String.match & RegExp.test
var pattern = new RegExp("/p[0-9]*/");
var className = $('div').attr('class')
if (pattern.test(className)) {
var class = className.match(pattern)[0];
$('div').removeClass(class).addClass('p' + integer);
}
I would like to replace the class's suffix while preserving its prefix
DEMO:
http://jsbin.com/vozufura/4/edit
The desired code should make all the div black.
So that:
class= menu-456 AND menu-789 should be replaced and become menu-123
All the div should be black as a result
HTML:
<div class="menu-123">black</div>
<div class="menu-456">green</div>
<div class="menu-789" >red</div>
CSS:
.menu-123 {
background: black;
}
.menu-456 {
background: green;
}
.menu-789 {
background: red;
}
Javascript (Jquery):
/* I am not looking for javascript like removeClass nor addClass,
nor do i want to change the background.
I wanted to know if it is possible to REPLACE the suffix of a class*/
Use a combination of removeClass() and addClass() functions provided by jQuery, like this:
$(document).ready(function(){
$(".menu-456,.menu-789").removeClass("menu-456 menu-789").addClass("menu-123");
});
This code runs when the DOM is loaded and what it does is as follows:
It selects all elements with either class menu-456 or menu-789.
It removes classes menu-456 and menu-789 from those elements.
It gives the elements the class menu-123.
FIDDLE
your jquery
JS:
$(document).ready(function () {
$('[class^=menu-]').not('.menu-123').removeClass().addClass('menu-123');
});
you can you addClass and removeClass
DEMO
Changing and messing with classes is easy with jQuery.
Take a look at .addClass .removeClass.
You can use the Attribute Contains Selector or Attribute Contains Prefix Selector to be more general and effective in your code.
For example, if you want menu-123 to be the only new class on the element:
$("div[class|='menu']").attr('class', 'menu-123');
or, if you want to get clever:
$("div[class|='menu']").attr('class', function(i, c){
return c.replace(/(^|\s)menu-\S+/g, 'menu-123');
});
thanks to this answer.
can you please tell me how to apply css all element whose starting element is same.Example I want to apply css whose starting characters of ID is "abc" ?
You can use pure CSS which is better:
[id^="abc"] {
// Your styles here
}
If you're looking for jQuery solution then you can use attribute starts with selector along with .css():
$('[id^="abc"]').css("Your styles here");
You can use Attribute Starts With Selector [name^="value"]
jQuery, css function
Live Demo
$('[id^=abc]').css('key', 'value');
css
Live Demo
[id^="abc"] {
background-color:red;
}
You can do it easily via css itself:
[id^="abc"] {
// mention your style here
}
Insert the above code in your css stylesheet file.
When using jQuery and are using the .attr method as follows:
$(document).ready(function(){
$('.class1').click(function(){
id = $(this).attr('.class2');
});
});
Say I have the following HTML for the above function:
<div class="class1 $class2"></div>
The second class is attributed at runtime, so I have 10 divs, each with class1, but several with class2. Then I wish to use the jQuery function at the top, so that whenever I click on any of the divs, it applies the specific class2 of that div, to the variable ID.
I hope this makes more sense.
Since your class2 comes from your PHP code, you seem to hit the usecase of data-attributes.
With data-attributes you can easily have some extra data (often used for javascript purposes) on your HTML elements without having to use special classes or ids for that.
It works like that:
<span data-hero="batman">I'm a Bat!</span>
Where in your Javascript (using jQuery) you get the value of it by simply doing:
$('span').data('hero');
Refer to the MDN and the jQuery documentation for further information.
Is this what you're trying to do?
$(document).ready(function(){
$('.class1').click(function(){
var id = $(this).attr('class').replace('class1','').trim();
});
});
If you have a multi class tag this mean the HTML code would be like this:
<sometag class="class1 class2">...</sometag>
I think the simplest approach is to do some string operations on the class attribute of the tag:
var class2 = $(selector).attr("class").split(" ")[1];
OR you can write a simple jQuery plugin to do the work for you:
(function($){
$.fn.secondClass = function(){
var c = this.attr("class").split(" ");
if(c.length >= 2)
return c[1];
};
}(jQuery))
Usage: var class2 = $(selector).secondClass();
Hope this helps.
I have a series of images tagged with HTML5 data descriptor "data-type2=[x]" where x is a number of different elements.
e.g.
<img data-type2="pants" class="element" src="#>
I am trying to pass that data field into a jquery function that finds classes in another div (<div class="outfit-list") that has child divs tagged with classes such as:
<div class="pants-001">
<div class="pants-002">
<div class="shoes-001">
etc.
Here is where I am stumped: how do I write a jquery function that accesses data type2 from the item I click (e.g. data-type2="pants"), finds all other divs under .outfit-list with classes that have, for example, "pants" in their class name "pants-002", and hide them? The function I have below does not work - I suspect that's because it's looking for the full name and not partial.
How do I make it perform a partial search to locate the classes that contain the term from data-type2?
<script type="text/javascript">
$(document).ready(function(){
$('.thumbslist .element').click(function(){
$('.outfit-list').find('.'+$(this).data('type2')).hide();
});
});
</script>
You can use the attribute contains selector, [attribute*="value"].
$('.outfit-list').find('[class*="' + $(this).data('type2') + '"]').hide();
You can use the starts with selector. Something like
$(".thumbslist .element").click(function() {
var type2 = $(this).data("type2");
$(".outfit-list").find("div[class^=" + type2 + "]").hide();
});
This plugin adds support for data selectors: http://plugins.jquery.com/project/dataSelector
First of all, the jQuery .data() method is amazing: http://api.jquery.com/data/
You could do:
$("#img1").data('type', 'pants')
// Or whatever else you need to attach data to. You can do this dynamically too!
t = $("#img1").data('type')
// Recall that data at some point
$("div").each(function() {
pat = new RegExp(t)
if ($(this).attr('class').search(pat) !== -1) {
$(this).hide()
}
});
Or even better in Coffeescript
t = $("#img1").data 'type'
$("div").each ->
if ($(#).attr('class').search new RegExp t) isnt -1 then $(#).hide()
May be with something like in this other question
jQuery selector regular expressions
You could just grab the value of the attribute then use it in an attribute selector: http://jsfiddle.net/n73fC/1/