I have several div's with a classname that looks like this:
class="col-md-4"
some have:
class="col-md-12"
What I want to do is to search for whatever the number at the end of the class is and replace all of them to:
class="col-md-6"
How can I do this using jQuery?
You can use special selectors in jQuery:
^= starts with ...
*= contains ...
Or use a combination of both selectors if you don't get them all.
var cols = $('[class^="col-md-"]');
Then to remove all classes with a wildcard
cols.removeClass(function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
});
Then add the class you want:
cols.addClass('col-md-6');
Try to remove the class and add the new one:
$(".col-md-4").removeClass("col-md-4").addClass("col-md-6");
$(".col-md-12").removeClass("col-md-12").addClass("col-md-6");
you can use "contains" selector like this
$("[class*='col-md-']").removeClass (function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
}).addClass("col-md-6");
removeClass function based on this answer
$("[class*='col-md-']")
will find any element with a class that contains col-md-.
The removeClass function will than remove it. And finally col-md-6 will be added.
EDIT
changed [class^='col-md-'] to [class*='col-md-'] in case class attribute has another class before col-md-. Thank you #dfsq for pointing this out
This should also work:
$('[class*=col-md]').removeClass('col-md-4 col-md-12').addClass('col-md-6');
You could do it with simple javascript if all of those elements were inside a main div.
For example:
var arr_divs = document.getElementById('main_div').getElementsByTagName('div');
for(var i = 0; i < arr_divs.length; i++){
if(arr_divs.item(i).className == 'col-md-12' || arr_divs.item(i).className == 'col-md-4'){
arr_divs.item(i).className = 'col-md-6';
}
}
This may not be the most efficient way of doing what you want but, it keeps it simple. Here's a working fiddle: https://jsfiddle.net/Lns1ob5q/
$("[class^=col-md-]").attr("class", "col-md-6");
The above selects all elements with a class containing col-md- ([class^=col-md-]) and replaces the class, regardless of what number immediately follows, with col-md-6.
The reason I say it's not efficient is becuase jQuery will initially pick up elements that already have a class of col-md-6 and replace their class with the same one... But hey, it works!
Related
I have an element with many classes, I would like to access a specific class to get the last digit of it (I realize a data-attribute or ID may have been better options but for now I am stuck with class). I already am able to select the element using it's ID so I only need to identify what the last digit of the my-target-* is.
Example
<div class="foo bar apple my-target-1"></div>
I would like to get the class my-target-* and then extract the 1 from it.
Loop over all the elements containing 'my-target', assuming it is the last class, split the classes by space, get the last class, split it by '-' then get the needed value to extract.
Here is a working example:
$(document).ready(function(){
$("[class*= my-target]").each(function(){
var extract= $(this).attr('class').split(' ').pop().split('-').pop();
$("#result").html(extract);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo bar apple my-target-1"></div>
<span id="result"></span>
Here's a jQuery selector that should target your element:
$("[class*=my-target]");
But this may be more general than you need: this uses the CSS substring selector *=, so this would also match elements like the following:
<div class="not-my-target"></div>
You can try a combination of selectors to get something more specific:
$("[class^=my-target], [class*= my-target"]);
This combines the CSS starts with selector, with the contains.
Now to grab the data that you want from the class name you'll need to do some string parsing on the class attribute:
var numberToExtract = -1;
var elem = $("[class*=my-target-]");
if (elem)
{
classes = elem.attr("class").split(/\s+/);
$.each(classes, function(idx, el)
{
if (el.startsWith("my-target-"))
{
numberToExtract = el.split("-").pop();
return false;
}
});
}
Maybe is neater if you use a data element to do this
<div class="foo bar apple my-target-1" data-target="1"></div>
And you get this by doing:
$('.my-target-1').data('target')
It's better than parsing the class
To get any one starting with those classes try this
$('div[id^=foo bar apple my-target]')
If you're stuck using a class instead of a data attribute, you can extract the full string of classes from the object you've found with:
obj.attr('class')
and then match that against a regular expression that uses word boundaries and capturing parentheses to extract the number at the end of 'my-target-*'
You must have ID to catch the particular div or span content.
Be Careful , Perhaps , you have a class and a subclass .
<div id='id' class='myclass mysubclass' >Testing</div>
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 class=$('.'+$('#id').attr('class').split(' ').join('.'))
that means
var class=$('.myclass.mysubclass')
If you want second class into multiple classes using into a element
var class_name = $('#id').attr('class').split(' ')[1];`
or You can simply use var className = $('#id').attr('class'); this will return full name class and subclass then handle it using JQuery/JavaScript substring method.
I am trying to add a class to a newly appended DIV without using something like:
t.y.append('<div class="lol'+i+'"></div>');
Here's a better example of what I'm trying to do:
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
t.y.append('<div></div>').addClass('lol'+i);
});
Page load HTML looks like:
<div class=".slideButton0 .slideButton1 .slideButton2" id="sliderNav">
<div></div>
<div></div>
<div></div>
</div>
When you append an element through .append, it doesn't change the context of the jQuery object.
You could write it like this:
$('<div></div>').appendTo(t.y).addClass('lol'+i);
or
$('<div></div>').addClass('lol'+i).appendTo(t.y);
(these both do the same thing, simply in different orders, the second possibly being more clear)
the context of the jQuery object will be the newly created div.
t.y.append('<div></div>').addClass('lol'+i);
should be
t.y.append('<div></div>').find('div').addClass('lol'+i);
In the first case you are adding class to the div to which you are appending ..
SO the context is still the parent div and not the newly appended div..
You need to find it first inside the parent and then add the class..
EDIT
If you want to just add the class to the last appended element ... Find the last div in the parent and then add the class to it..
This will make sure you are not adding the class to all the div's every single time you iterate in the loop..
t.y.append('<div></div>').find('div:last').addClass('lol'+i);
Try this:
t.y.append($('<div></div>').addClass('lol'+i));
Fiddle: http://jsfiddle.net/gromer/QkTdq/
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
var d = $('<div />').addClass('lol' + i);
t.y.append(d);
});
The problem is that append returns the container instead of the thing you just appended to it. I would just do the addClass before the append instead of after:
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
t.y.append($('<div></div>').addClass('lol'+i));
});
EDIT ... or, in other words, exactly what Gromer said. Beat me by five whole minutes, too. I'm getting slow.
You don't mention why you want to number the class attribute to your list items, but in the case that you are actually using them for css don't forget you have :odd and :even css selector attritbutes and also the equivalent odd/even jQuery selectors.
http://www.w3.org/Style/Examples/007/evenodd.en.html
http://api.jquery.com/odd-selector/
I didn't find anything like this. notice the class attribute!
$.each(obj, function (_index, item) {
resultContainer.append($('<li>', {
class: "list-group-item",
value: item.id,
text: item.permitHolderName || item.permitHolderId
}));
});
This finds the id but does not remove the class
$('[id^=paritalIDname]').removeClass('[class^=partialClassName]');
Probably because the element looks like
<div id="partialIDname-full" class="something someone partialClassNameFull">
Whether the element has a class name of partialClassNameFull or partialClassNameHalf I need to remove it.
I thought I could use a wildcard in the class selector, like
removeClass('[class^=partialClassName*]');
but that's not working.
What is a good solution? (Thanks.)
This will handle all partial match.
$("div[id^=partialId]").each(function () {
var cls = $(this).attr("class").split(" ");
for (var i in cls) {
if (/partialClass/.test(cls[i])) {
$(this).removeClass(cls[i]);
break;
}
}
});
You need to explicitly remove both classes:
$('[id^=partialIDname]').removeClass('partialClassNameFull').removeClass('partialClassNameHalf');
Because .removeClass() only works on full class name matches. If one of the class names is not present, then nothing will happen - no error is thrown when you try to .removeClass() a class that is not present.
You can also try out as suggested in the comments the briefer version of:
$('[id^=partialIDname]').removeClass('partialClassNameFull partialClassNameHalf');
I need to use jQuery to locate all DIV tags that have no attributes on them and apply a class to each. Here's a sample HTML:
<div id="sidebar">
<div>Some text goes here</div>
<div class="something">something goes here</div>
<div>Another div with no attributes.</div>
</div>
So, I need to take that and turn it into this:
<div id="sidebar">
<div class="myClass">Some text goes here</div>
<div class="something">something goes here</div>
<div class="myClass">Another div with no attributes.</div>
</div>
How do you locate elements of type div that have no attributes via jQuery? Thanks.
Here you go:
$('div', '#sidebar').filter(function () {
return this.attributes.length === 0;
})
Live demo: http://jsfiddle.net/phbU9/
The attributes property returns a list of all attributes set on the element. "Naked" elements have an empty attributes list.
Update: Be sure to read Tim's answer below which provides a solution for older versions of IE, since my own solution doesn't work in IE8 and below.
#Šime's answer is close but doesn't work in IE 6, 7 or 8, where an element's attributes collection has an entry for every possible attribute, not just those specified in the HTML. You can get round this by checking each attribute object's specified property.
Live demo: http://jsfiddle.net/timdown/6MqmK/1/
Code:
$("div").filter(function() {
var attrs = this.attributes, attrCount = attrs.length;
if (attrCount == 0) {
return true;
} else {
for (var i = 0; i < attrCount; ++i) {
if (attrs[i].specified) {
return false;
}
}
return true;
}
});
check this out:
http://jsfiddle.net/thilakar/CHux9/
You need to give some sort of selector, in this case Ive used your side bar but it can be anything. Then get the children that have no class attribute and add a new class. See JSFiddle for the example:
http://jsfiddle.net/HenryGarle/q3x5W/
$("#sidebar").children('div:not([class])').addClass('newClass');
So this would return the 2 elements with no class tag and leave the sidebar and div with the class completely unaffected.
You could use a combination of jQuery's has attribute selector and the not selector. For example:
$('div:not([class], [id])').addClass('myClass');
jsFiddle demonstrating this
With this approach, you need to explicitly specify the attributes to check the presence of. Sime's solution would apply the class to divs that do not have any attributes at all.
To expound upon Tim Down's answer, I recommend checking that the attrs var not null special cases where the html has comment tags, etc.
try $('div:not([class])').addClass('myClass');
it is a general approach because the class will apply to all the div that have no class
$('#sidebar div')` or more general `$('div'); //returns collections of divs
to answer the question:
$('#sidebar div').addClass('myClass');
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/