Richard Adams
Richard Adams

Reputation: 1

Using javascript to set an HTML class name

Is it possible to put a javascript function call in place of a HTML class name so that the class can be set based upon the results of the function? For example, something like:

<a class="fSetClass(vName)" ....

which would call a function named fSetClass() and receive back a valid CSS class name based upon the parameter vName passed with it.

Thanks

Upvotes: 0

Views: 4318

Answers (6)

skadermen
skadermen

Reputation: 58

Smth like this, if in short way
document.onload = function(){
document.getElementById('your-element-id').className = fSetClass(vname);
}

Upvotes: 1

rahool
rahool

Reputation: 639

If you use jquery, you can set the class by using .attr():

$(document).ready(function() {
  function fSetClass(vName){
     $("#element_id").attr('class', vName);
  }

  fSetClass('className');

});

Upvotes: 0

Mark Shust at M.academy
Mark Shust at M.academy

Reputation: 6429

If you use jQuery, you can use the addClass function

$(element).addClass('add-this-class');

If you want to set the class instead, use attr:

$(element).attr('class','add-this-class');

Upvotes: -1

Felix Kling
Felix Kling

Reputation: 816322

Only the on* event handler attributes are evaluated as JavaScript code, the other attributes are not.

As already said, you have to assign the class normally with JavaScript. Assuming you have a reference to the element (element), you have to assign the class to the className [MDN] property:

element.className = fSetClass(vname);

Upvotes: 0

evasilchenko
evasilchenko

Reputation: 1870

No but what you can do is use jquery to get the item and then add or remove class names from it:

HTML

<div class="my-class">My Content</div>

jQuery

// will produce <div class="my-class added-class">My Content</div>

var addClass = 1;

if(addClass == 1) {
    $(".my-class").addClass("added-class");
}
else
{
    $(".my-class").removeClass("removed-class");
} 

Upvotes: 0

scottheckel
scottheckel

Reputation: 9244

No, it's not possible to do what you're asking from within the HTML. Though, you can use JavaScript to add the class to it afterward.

Upvotes: 1

Related Questions