Reputation: 231
I feel like this is a stupid simple question, but I've been doing so much CSS work lately that I feel a little rusty. So, I have several buttons with classname: and class: attributes. Basically, all I want to do is take the value of the classname attribute and append it to class. Only the buttons with className need their content appended.
classname="blah_btn blah_btnGrey" class="blah blah blah foo foo"
Would I write something like:
if ($('#ui-button').has("className")) {
$(("className").val()).appendTo("class");
or something more along the lines of:
$("button").each(function() {
//do stuff
});
Or am I in the completely wrong ballpark? Once again, any help is greatly appreciated.
Upvotes: 1
Views: 114
Reputation: 1951
How about this?
$('button[className]').each(function(){
var classNameValue = $(this).attr('className');
var classValue = $(this).attr('class');
$(this).attr('class', classValue + classNameValue);
});
Upvotes: -1
Reputation: 707406
First off, please don't use an attribute call className
. That is reserved as the way to address the class
attribute because class
is a reserved word in javascript. So, if you use attributes with names of class
and className
, you could end up having a hard time reaching them individually in javascript. It could be a mess. Pick a more unique name for the one that isn't actually class
.
To add the class attribute, you would just use .addClass()
:
$('#ui-button').addClass("blah_btn")
jQuery's `addClass() is smart enough to not add it if it's already present.
If you want to get an attribute and add it to the actual class, you can do this:
$('#ui-button').addClass($(elem).attr("myAttribute"));
If you just want to add one attribute onto another, you can do this:
var target = $('#ui-button');
target.attr(target.attr("myAttribute") + $(elem).attr("myAttribute"));
Upvotes: 2
Reputation: 26320
That's what you need ?
$.each($('#ui-button.className'), function() {
var $element = $(this);
$element.addClass($element.val());
});
Upvotes: 1