Using javascript to set an HTML class name - javascript

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

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.

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

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

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

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

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

Related

How to pass variable from javascript into jquery?

I have the following code,
<a href="#" onclick="popup('<?php echo $temp_class['class']; ?>')">
I pass a class generated from php function to javascript function popup().
I have another code
function popup (myclass) {
$(myclass).hide();
}
The variable myclass accept value passed to the function. How to use myclass value to jquery so that I can hide an html element associated with the given class like example above?
The dot is used for classes so I think this will work:
$('.' + myclass).hide();
Expanding on Wouter's answer a bit.
The dot class is needed for classes but it might also be worth checking if it already exists.
function popup (myclass) {
if(myclass.charAt(0) === '.'){
//If we already have a '.' just hide.
$(myclass).hide();
} else {
$('.' + myclass).hide();
}
}
This will make the function more flexible.
Did you think to add . to your selector ?
Because in jquery, the selector for class named myClass is .myClass like in css.

Using jQuery, how to specify with the `.attr` method, the second of two html classes?

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.

Add/remove/replace the class for html element

I'm curious about how can I add/remove class to html element? It seems to be a very simply operation. But it turned out that the method removeClass was not found for some reason.
So what I need to do is replace or remove an old one and add a new one to an element. How can I do that?
The removeClass method is included in jQuery, unless you've overridden it.
$("#someElement").removeClass("someclass");
Use AddClass to add class, removeClass to remove, toggleClass to toggle (removes class if exists or adds if does not exist) :)
If you use jQuery make sure it is loaded before your script and then use like this:
$('p').removeClass('myClass yourClass') // remove class
$("p").addClass("myClass yourClass"); // add class
if you want to use pure JS here you are : How do I add a class to a given element?
var d = document.getElementById("div1");
d.className = d.className + " otherclass";
Use addClass and removeClass
<div class="firstClass" id="uniqeId"></div>
$("div#uniqeId").removeClass("firstClass");
$("div#uniqeId").addClass("Some_Other_Class");
$('#elementId').addClass('className');
$('#elementId').removeClass('className');
See: http://api.jquery.com/category/manipulation/class-attribute/
Since your question is tagged with jquery, there are two functions you can use:
$(element).removeClass('oldclass')
$(element).addClass('newclass')
Without jQuery and on modern browsers you can work with the classList property:
element.classList.remove('oldclass')
element.classList.add('newclass')
You can use .toggleClass() to add/remove simultaneously, i mean switch from one class to another:
Description from the docs
Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
if this is your html:
<div class="aaa">Some text.</div>
then this script:
$('div.aaa').toggleClass('bbb');
will output like this:
<div class="aaa bbb">Some text.</div>
Or if you do this:
$('elem').toggleClass('aaa bbb');
//--------------------^^^---here this class will be added/removed

Getting attribute of a parent node

I am trying to use
$(this).parentNode.attr('data-element')
which should return 0 - 5 in string but it just won't work. I am using it in a function like this
$('.someClass').each(function(){
$(this).html(SomeFunction('SomeString', $(this).parentNode.attr('data-element')));
});
All the elements with class 'someClass' have a parentNode
<li class="element" data-element: 1 (or any number from 0 to 5 (including))> </li>
and I have no idea where is the mistake. What am I doing wrong?
--David
You are mixing jQuery and plain javascript in the same line of code and that will not work. You can either use:
$(this).parent().attr('data-element'); // jQuery
or
this.parentNode.getAttribute("data-element"); // plain javascript
parentNode is not a property of a jQuery object, so you can't mix the two the way you were doing it. The jQuery method for getting the parent is .parent().
You should do
$(this).parent().attr('data-element')
because you can't call attr() on a non jQuery object
Try doing this instead:
$(this).parent().attr('data-element');
For more information on functions like .parent() see the Traversing section of the JQuery documentation:
http://api.jquery.com/category/traversing/
Using jquery it should be:
$(this).parent().attr('data-element');
Without using jquery this would be:
this.parentNode.getAttribute("data-element")
I prefer to use:
var item = $(this);
var parent = item.closest(".element"); //using the class for selection
//and then use parent.attr('data-element')

How to execute partial find on dynamic HTML5 data descriptor?

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/

Categories