0

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

3
  • And that class name would be set once in the initialization of the page? Then PHP/C#/... Commented Jan 5, 2012 at 20:28
  • 1
    No, but you can use JavaScript to change the classname of an element, (though you can't do something like class="fSetClass()" and expect it to work. This is more of the PHP realm really, not JavaScript. Commented Jan 5, 2012 at 20:28
  • do you mean like addClass() or removeClass() functions of jquery? Commented Jan 5, 2012 at 20:28

6 Answers 6

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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");
} 

Comments

0

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);

Comments

0

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');

});

Comments

-1

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');

2 Comments

And what if he is not using jQuery?
adding a class != setting a class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.