jQuery, selecting just number from id like "article-23" - javascript

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

Related

How do I iterate through div's child elements and hide them?

I have a div that have a few elements that I want to hide, on users request. Those elements have a particular background color. The call of the function is working (it is associated to a checkbox) but it just doesnt do what i want. Actually, it does nothing. This is what I've got:
function toogleDisplay()
{
var kiddos= document.getElementById('external-events').childNodes; //my div
for(i=0; i < kiddos.length; i++)
{
var a=kiddos[i];
if (a.style.backgroundColor=="#A2B5CD")
{
if (a.style.display!="none")
{
a.style.display='none';
}
else
{
a.style.display='block';
}
}
}
}
What am I doing wrong?
An element's background colour is converted to rgb() (or rgba()) format internally.
But that aside, assuming $ is jQuery (you haven't tagged your question so I don't know!) then a is a jQuery object, which does not have a style property. It looks like you just wanted var a = kiddos[i];.
It is more reliable to use a specific class name instead.
You re wrapping your kiddos[i] in a jquery-object $(kiddos[i]) and then try to access the normal properties of a html-dom-objekt.
You have 2 possibilities:
remove the $()
use jquery-access to the properties
a.css('display', none); // or just a.hide();
Additionally you cant check for '#123456' since the color is transformed. Check (#Niet the Dark Absol)s answer for this
I would suggest adding a class to the elements you want to check. Then instead of trying to use background, you can do
$(kiddos[i]).hasClass('myclass')
or for a very efficient way, you can do it in one line of code.
function toogleDisplay()
{
$('.myclass').toggle(); //this will toggle hide/show
}
The divs would look like this
<div class='myclass'>Content</div>
EDIT - to do it without modifying existing html. I also think the rbg color should be rgb(162, 181, 205) if im not mistaken.
You can try something like this. Its based off the following link
Selecting elements with a certain background color
function toogleDisplay()
{
$('div#external-events').filter(function() {
var match = 'rgb(162, 181, 205)'; // should be your color
return ( $(this).css('background-color') == match );
}).toggle()
}
Your jquery selection of a is causing issues. Unwrap the $() from that and you should be fine.
Also you could end up selecting text nodes that wont have a style property. You should check that the style property exists on the node before trying to access background, display, etc.
Use a class instead of a background and check for that instead.
i think you need to see if the 'nodeType' is an element 'a.nodeType == 1' see Node.nodeType then it will work over multiple lines
var kiddos= document.getElementById('external-events').childNodes; //my div
for(i=0; i < kiddos.length; i++)
{
var a=kiddos[i];
if (a.nodeType == 1){ // Check the node type
if (a.style.backgroundColor=="red")
{
if (a.style.display!="none")
{
a.style.display='none';
}
else
{
a.style.display='block';
}
}
}
}
I decided to go for another aproach, using the idea of Kalel Wade. All the elements that may be (or not) hidden, already had a class name, which were the same for all elements, fortunately.
here comes the code
function toogleDisplay()
{
var kiddos = document.getElementsByClassName("external-event ui-draggable");
for (var i = 0, len = kiddos.length; i < len; i++) {
var a=kiddos[i];
if (a.style.backgroundColor==="rgb(162, 181, 205)")
{
if (a.style.display!="none")
{
a.style.display='none';
}
else
{
a.style.display='block';
}
}
}
}

Need to get is any child inside an element is having a background

I need to find out is their any span having a style of background so I can get value from its attribute I have $(this). Structure is:
<div id="operative_time_limit" class="timedivd">
<span title="1 hours" data-y="1" data-x="0"></span>
<span title="2 hours" data-y="2" data-x="0"></span>
<span title="3 hours" data-y="3" data-x="0"></span>
<span title="4 hours" data-y="4" data-x="0"></span>
</div>
Using alert(jQuery(this).children().css('background').length); but always getting 0 as result
try this,
alert($('#operative_time_limit').find('span').length);
For span which has background-color property then try it like,
var c=0;
$('#operative_time_limit').find('span').each(function(){
if($(this).css('backgroundColor')) // or 'background-color'
c++;
});
alert(c);
I am not sure what exactly $(this) is in your context.
However the following:
var count = 0;
$('#operative_time_limit span').each(function(index){
if($(this).css('background')){
count++;
}
});
alert(count);
Will do it. Further extrapolating from your question to presume that you want to extract some attribute (lets call it someAttr), from the span with a background of css, and there is only one such span. Assuming those are correct assumptions, the following will give you what you want:
var attributeValue;
$('#operative_time_limit span').each(function(index){
if($(this).css('background')){
attributeValue = $(this).attr('someAttr');
}
});
You now have your desired value in attributeValue
The following line will give you the length of Children of $(this)
alert(jQuery(this).children().css('background').length);
You could use the following code to find all the span's that have background color other than white (assuming white is default color)
var length = $('#operative_time_limit').children().filter(function () {
return $(this).css('background-color') != 'rgba(0, 0, 0, 0)' && $(this).css('background-color') != 'transparent';
}).length;
here, variable length can be used to determine how many spans have background property
See working fiddle
use following
alert(jQuery(this).children().hasClass('background')).
hasClss determines whether any of the matched elements are assigned the given class.
The .hasClass() method will return true if the class is assigned to an element, even if other classes also are

search contents of a div with multiple classes for a string nested in elements with jQuery

I would like to be able to look in the first span within a div with a class of t_links and buy and detect if the string Account appears. If it does then I want to set some tracking code in jQuery/JavaScript.
There will always be one span within this div. How can I search the contents for an instance of Account using jQuery?
<div class="t_links buy">
<span><a class="" href="https://www.ayrshireminis.com/account/login/">Account</a></span>
</div>
:contains is what you're looking for:
$(".t_links.buy span:first:contains('Account')")
http://api.jquery.com/contains-selector/
Edit: Added first as #adeneo pointed out. This will ensure that it's the first span that you're looking at.
Try (See Demo)
​$(document).ready(function () {
if($('.t_links.buy span').text().indexOf('Account')) {
// code
}
});​
Or
​$(document).ready(function () {
if($(".t_links.buy span:contains('Account')").length) {
// code
}
});​
Span has exact match :
if ($("span:first", ".t_links.buy")​.filter(function() {
return $(this).text() === 'Account';
})​.length) {
//set tracking code
}
Span contains :
if ($("span:first", ".t_links.buy")​.filter(function() {
return $(this).text().toLowerCase().indexOf('account') != -1;
})​.length) {
//set tracking code
}
If there is only one span, you can drop the :first.

Need to add multiple elements to search for a particular class with jQuery

I am using jQuery and am currently looking in one type of element for a particular class. I need to update it to look in three different elements, but am not sure how to do this since I assume I will need to use an array?
Here's my current code:
$findRed = $("p.red", "#main");
if ( $findRed.length >= 1 ) {
greater or equal to one
}
I need to change it so it will look for .red in either a p, div, or span tag.
Any help would be appreciate.
Your selector can simply be .red. That will match any element type with that class. Or if you just want those specific elements, your selector could look like this:
$findRed = $("p.red, div.red, span.red", "#main");
var $findRd = $(":has(.red)", $("p, div, span", $("#main")));
try this:
$findRed = $("p.red", $("#main, #main2, #main3"));
//will look in main, main2 and main3
if ( $findRed.length >= 1 ) {
greater or equal to one
}
if ($("p > .red, div > .red, span > .red").length > 0){
// do something here
}

Can someone explain the following javascript code?

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

Categories

Resources