I'm currently using this to get the class for a specific bit of HTML on the page:
$(this).parent("div").attr('class')
But that div has multiple classes: current_status status_billed
My end goal here is to grab the class that starts with status_ and replace it with a different class name.
So using my .parent() function above, I'm able to select the div I need, but I then need to remove the status_billed class and replace it with, for example, status_completed (or a number of other class names).
Select divs that have the status_billed class:
$(this).parent('div.status_billed')
Select divs whose class attribute contains status_:
$(this).parent('div[class*=status_]')
That's about the best you'll get with jQuery selectors. You can do better using .filter():
$(this).parent('div').filter(function ()
{
var classes = $(this).attr('class').split(' ');
for (var i=0; i<classes.length; i++)
{
if (classes[i].slice(0,7) === 'status_')
{
return true;
}
}
return false;
});
...but I'm not sure why you're doing all this - .parent() returns at most 1 element. Did you mean .closest() or .parents()?
Related
I'm in a situation where I want to check if two elements (one is clicked and another one a reference) are the same, what I'm trying to do is:
$("#process li").click(function() {
currentElement = $(this);
referenceElement = $("#process li:first-child");
if (currentElement === referenceElement) {
$(".mark").removeClass("mark");
$(this).addClass("mark");
}
});
So what I want is to check if the clicked <li> is the first child of the ul#process and if so first remove a .mark class from another element and then add it to the clicked one. I don't get any working result - ideas anyone?
UPDATE:
Thanks you very much! This is my solution:
$("#processlist li").click(function() {
currentElement = $(this);
if (currentElement.is('li:first-child')) {
$(this).addClass("mark");
}
});
Now if I click on a , if it is the first child of this list, the class .mark is added - sweet!
Comparing objects in JS is very troublesome. The simplest way is to just pick a few key properties and compare those, eg:
if (currentElement.prop('id') === referenceElement.prop('id') {
// rest of your code...
}
However, given your use case you could use is:
if (currentElement.is('#process li:first-child')) {
// rest of your code...
}
Example fiddle
You need to extract the DOM element from the jQuery object. You can use the get method of jQuery for this.
e.g. if( currentElement.get( 0 ) === referenceElement.get( 0 ) )
I have an event in which I need to add a class to an element with a matching class name.
For example:
<a class="one"></div>
<a class="two"></div>
<div class="one"></div>
<div class="two"></div>
How do I find and add an additional class to the element with the matching class name?
Here is my script, I need it to target the tag with matching class.
jQuery('div.two').waypoint(function(direction) {
if (direction === 'down') {
jQuery(this).addClass("active") // to <a> element that shares same class
}
else {
}
});
I'm not familiar with this plugin but I'll give it a shot. Based off what you've provided I think your problem is:
jQuery(this).addClass("active")
Since you already know the class, just do:
var tempClass = $(this).attr("class");
jQuery("a."+tempClass).addClass("active");
Just select by class names.
Array.prototype.forEach.call(document.querySelectorAll(".one"), function(el) {
el.classList.add("whateverClass");
});
Instead of a for loop, this uses the prototype method forEach with the call method to turn the NodeList into an array list, adding the class to each element with the class "one"
DEMO
You probably want to remove the class from the others first, then add to the applicable <a>
jQuery('div.two').waypoint(function(direction) {
if (direction === 'down') {
/* remove prior active class */
jQuery("a.active").removeClass('active');
/* add to current one */
jQuery("a.two").addClass('active');
}
else {
}
});
To make this more generic I would add a class like waypoint to all the content elements as well as a data-point to be able to simplify instances.
<div data-point="one" class="waypoint"></div>
JS
jQuery('.waypoint').waypoint(function(direction) {
if (direction === 'down') {
/* remove prior active class */
jQuery("a.active").removeClass('active');
/* add to current one */
var linkClass=$(this).data('point')
jQuery("a." + linkClass).addClass('active');
}
else {
}
});
I am using jQuery to count divs and would like to have a class added once it counts 20.
ie: divs 1-20 are class="box" and divs 21 + are class="box new"
This is what I have but it adds the "new" class to all the divs.
$(function() {
var divCount = $("#content").children(".box").length;
if (divCount > 20) {
$(".box").addClass("new");
}
});
$(".box:gt(20)").addClass("new");
Just want to point out that you can do this with just CSS using nth-child. Of course, if you're using the class for targeting you still may want to go the jQuery route:
div.box:nth-child(n+21) {
... new styles go here
}
See more here: http://css-tricks.com/useful-nth-child-recipies/
Something like this should work:
var i = 0;
$("#content").children(".box").each(function(i, k) {
if(++i > 20) $(k).addClass("new");
});
or
$("#content").children(".box").each(function(i, k) {
if($(k).is(":gt(20)")) $(k).addClass("new");
});
Take into account that your code says as follows:
If there are more than 20 boxes, add class 'new' to all the divs with class 'box'. And so, all the boxes are selected.
In this case, I recommed using the :gt() selector: gt-selector - jQuery
Therefore:
$(function() {
$(".box:gt(20)").addClass("new");
});
You can use this cheatsheet if you're not sure which selector to use: Oscar Otero jQuery Cheatsheet
Your code:
if (divCount > 20)
is actually checking a condition for truthfulness and adding a class "new" to all elements that have the class .box because the condition passes the test when you have more than 20 divs.
What you want to do is loop through the elements and check for truthfulness of your condition inside that, applying the new class to the current element if it's index is above 20 - 1 (counting starts at zero, so your element with an index of 19 will be your 20th element).
$(function() {
$.each($("#content").children(".box"), function(index, value){
if ( index - 1 > 20 ) {
$(this).addClass(".new");
}
});
});
All right, I have a div tag which got a class="blog-post" and id like id="article-23" (where "23" could be any number, as it is id of blog post in a database). I need to somehow get just a number from that id and than apply some rules to that div tag. So say:
if number from id % 2 == 0 {
set text colour black to associated div tag with class of blog-post
} else {
set text colour white to associated div tag with class of blog-post
}
Thats just a "pseudo" code to show logic that I wan't to apply dependent if number from id is even or odd, but the question remains same, how do I just get number from id like "article-23" ?
As simple as
var number = "article-23".match(/\d+/)[0];
But you have to be sure that any digit exists in the string, otherwise you'd get a error.
You can actually apply rules via function, which makes this the cleanest solution (in my opinion):
$(".blog-post").css('color', function () {
return +this.id.replace('article-', '') % 2 ? 'blue' : 'red';
});
http://jsfiddle.net/ExplosionPIlls/Jrc5u/
Try this:
$('.blog-post[id^="article-"]').each(function () {
if (parseInt(this.id.replace('article-', '')) % 2 === 0) {
$('#' + this.id).css('color', 'black');
} else {
$('#' + this.id).css('color', 'white');
}
});
jsFiddle Demo
As an alternative, HTML5 supports these things called "data attributes", which are specifically meant for attaching data to your DOM without abusing things like the "class" or "id" attributes. jQuery provides a handy .data method for reading these attributes in a more obvious way.
You can add your own numeric ID attribute using something like "data-id":
<div class="blog-post" data-id="23" />
$("#blog-post").each(function () {
console.log($(this).data("id")); // Look up the data-id attribute
});
If I'm understanding correctly, you want the number after the hyphen of the id tag of your .blog-post class.
var article = $(".blog-post").attr('id'); //get the id
var article = article.split("-"); // split it on hyphens
return article = article[article.length-1]; // return the last element
In addition to the explanation, what does the $ mean in javascript? Here is the code:
var ZebraTable = {
bgcolor: '',
classname: '',
stripe: function(el) {
if (!$(el)) return;
var rows = $(el).getElementsByTagName('tr');
for (var i=1,len=rows.length;i<len;i++) {
if (i % 2 == 0) rows[i].className = 'alt';
Event.add(rows[i],'mouseover',function() {
ZebraTable.mouseover(this); });
Event.add(rows[i],'mouseout',function() { ZebraTable.mouseout(this); });
}
},
mouseover: function(row) {
this.bgcolor = row.style.backgroundColor;
this.classname = row.className;
addClassName(row,'over');
},
mouseout: function(row) {
removeClassName(row,'over');
addClassName(row,this.classname);
row.style.backgroundColor = this.bgcolor;
}
}
window.onload = function() {
ZebraTable.stripe('mytable');
}
Here is a link to where I got the code and you can view a demo on the page. It does not appear to be using any framework. I was actually going through a JQuery tutorial that took this code and used JQuery on it to do the table striping. Here is the link:
http://v3.thewatchmakerproject.com/journal/309/stripe-your-tables-the-oo-way
Can someone explain the following
javascript code?
//Shorthand for document.getElementById
function $(id) {
return document.getElementById(id);
}
var ZebraTable = {
bgcolor: '',
classname: '',
stripe: function(el) {
//if the el cannot be found, return
if (!$(el)) return;
//get all the <tr> elements of the table
var rows = $(el).getElementsByTagName('tr');
//for each <tr> element
for (var i=1,len=rows.length;i<len;i++) {
//for every second row, set the className of the <tr> element to 'alt'
if (i % 2 == 0) rows[i].className = 'alt';
//add a mouseOver event to change the row className when rolling over the <tr> element
Event.add(rows[i],'mouseover',function() {
ZebraTable.mouseover(this);
});
//add a mouseOut event to revert the row className when rolling out of the <tr> element
Event.add(rows[i],'mouseout',function() {
ZebraTable.mouseout(this);
});
}
},
//the <tr> mouse over function
mouseover: function(row) {
//save the row's old background color in the ZebraTable.bgcolor variable
this.bgcolor = row.style.backgroundColor;
//save the row's className in the ZebraTable.classname variable
this.classname = row.className;
//add the 'over' class to the className property
//addClassName is some other function that handles this
addClassName(row,'over');
},
mouseout: function(row) {
//remove the 'over' class form the className of the row
removeClassName(row,'over');
//add the previous className that was stored in the ZebraTable.classname variable
addClassName(row,this.classname);
//set the background color back to the value that was stored in the ZebraTable.bgcolor variable
row.style.backgroundColor = this.bgcolor;
}
}
window.onload = function() {
//once the page is loaded, "stripe" the "mytable" element
ZebraTable.stripe('mytable');
}
The $ doesn't mean anything in Javascript, but it's a valid function name and several libraries use it as their all-encompassing function, for example Prototype and jQuery
From the example you linked to:
function $() {
var elements = new Array();
for (var i=0;i<arguments.length;i++) {
var element = arguments[i];
if (typeof element == 'string') element = document.getElementById(element);
if (arguments.length == 1) return element;
elements.push(element);
}
return elements;
}
The $ function is searching for elements by their id attribute.
This function loops through the rows in a table and does two things.
1) sets up alternating row style. if (i % 2 == 0) rows[i].className = 'alt' means every other row has its classname set to alt.
2) Attaches a mouseover and mouseout event to the row so the row changes background color when the user mouses over it.
the $ is a function set up by various javascript frameworks ( such as jquery) that simply calls document.getElementById
The code basically sets alternating table rows to have a different CSS class, and adds a mouseover and mouseout event change to a third css class, highlighting the row under the mouse.
I'm not sure if jQuery, prototype or maybe another third party JS library is referenced, but the dollar sign is used by jQuery as a selector. In this case, the user is testing to see if the object is null.
$ is the so-called "dollar function", used in a number of JavaScript frameworks to find an element and/or "wrap" it so that it can be used with framework functions and classes. I don't recognize the other functions used, so I can't tell you exactly which framework this is using, but my first guess would be Prototype or Dojo. (It certainly isn't jQuery.)
The code creates a ZebraTable "object" in Javascript, which stripes a table row by row in Javascript.
It has a couple of member functions of note:
stripe(el) - you pass in an element el, which is assumed to be a table. It gets all <tr> tags within the table (getElementsByTagName), then loops through them, assigning the class name "alt" to alternating rows. It also adds event handlers for mouse over and mouse out.
mouseover(row) - The "mouse over" event handler for a row, which stores the old class and background colour for the row, then assigns it the class name "over"
mouseout(row) - The reverse of mouseover, restores the old class name and background colour.
The $ is a function which returns an element given either the elements name or the element itself. It returns null if its parameters are invalid (non-existent element, for example)
I believe the framework being used is Prototype, so you can check out their docs for more info
Have a look at the bottom of the article that you have got the code from, you'll see that they say you'll also need prototype's $ function. From article
In your CSS you’ll need to specify a
default style for table rows, plus
tr.alt and tr.over classes. Here’s a
simple demo, which also includes the
other functions you’ll need (an Event
registration object and Prototype’s $
function).