I would like to display an increased number (starting with 1 and ending with 47) for each class called quiz_image.
The HTML looks kind of like this:
<div class="quiz_image">
Content here
</div>
<div class="quiz_image">
Content here
</div>
<div class="quiz_image">
Content here
</div>
In order to display the number before the class quiz_image, I have tried it like this:
var i = 1;
$('.quiz_image').before(i);
i++;
In my code above the number will not increase, since there is probably a loop needed and I have no idea how to start a loop in this case. I hope somebody can help out on this.
When you use jQuery to get a selector it will return an array of elements. So you'll want to loop through them. I would suggest with something like the jQuery .each() function, which natively provides you with a 0 based index, you could try something like:
$('.quiz_image').each(function(i){
$(this).before(i + 1); // add one so we dont start at 0
});
Loopin all quiz_image and use their index numbers
$('.quiz_image').each(function(index){
$(this).before(index+1);
});
Working Demo
before function in jQuery sets the content before the specified element , and it also accepts the function so we can do it like the below example.
index function Search for a given element from among the matched elements
$('.quiz_image').before(function(){
return $('.quiz_image').index(this)+1
});
Why do you want to change the class for each image?
Rather give each one an ID.
<div class="quiz_image"></div>
<script>
counter = 0;
var quiz_id = $(".quiz_image").prop("id");
$(".quiz_image").each(function(){
counter++;
quiz_id = quiz_id + counter
$(".quiz_image").prop("id",quiz_id);
});
Related
I'm using simplepie to pull in two rss feeds. Using a PHP foreach loop, I then echo the information each feed post contains in the class .story_overview and adding a .pin class for each article. I'm using jQuery within the PHP foreach to hide.story_overview and add a unique identifying number to the end of the .story_overview and respective .pin class and this is working:
<script>
$('.story_overview').hide();
$('.pin').attr('class','pin' + i);
$('.story_overview').attr('class','story_overview' + i);
i++;
</script>
I'm trying to reach the desired outcome of hovering over a .pin revealing the respective .story_overview (so .pin1 would reveal .story_overview1). I'm currently trying to do this with a JavaScript for loop but it refuses to work:
<script>
for (x = 0; x <= i; x++){
$('.pin'+ x.toString()).mouseover(function(){
$('.story_overview' + x.toString()).show();
});
$('.pin'+ x.toString()).mouseout(function(){
$('.story_overview' + x.toString()).hide();
});
};
</script>
I have tested all the jQuery commands by trying the same code but with the identifying numbers at the end of the class names (rather than x.toString) and placing the code outside of the for loop, and that all works.
Any help what so ever would be greatly appreciated! Thanks in advance.
You can simply do this:
$('.pin').mouseover(function(){
$('.story_overview').eq($(this).index()).show();
}).mouseout(function(){
$('.story_overview').eq($(this).index()).hide();
});
You can achieve the desired output by using the .eq() method with .index() to get the index of the hovered element.
Or you might like this:
$('.pin').mouseover(function(){
$('.story_overview'+$(this).index()).show();
}).mouseout(function(){
$('.story_overview'+$(this).index()).hide();
});
I'm trying to do something seemingly simple but it's turning out more difficult than I thought.
I have on a page 4 span elements (that I have no control over) all with the same class ID (BOfSxb) and I need to edit only two of them - the second and the 4th element. So I'm not sure how to select only those two and before I do that, I need to know the contents of the 2nd or the 4th span element (2 and 4 have identical content). I figured out how to get the contents but I'm getting both combined so if the content is 2,304,400 I'm getting back 2,304,4002,304,400
here's how I was able to get the content so far:
var spanContent = $("span.BOfSxb:contains(2,304,400)").text()
console.log(spanContent); //returns 2,304,4002,304,400 ( I need 2,304,400)
The other problem with the above is :contains has a number I won't know ahead of time.
After I get the content off the second or 4th span, I need to compare it and see what range it falls under and do something else with it. Something like:
if ($(".BOfSxb:contains("+ spanContent + ")").text() >= 0 && $(".BOfSxb:contains("+ spanContent + ")").text() <= 1000) {
$("span.BOfSxb:contains("+ spanContent + ")").replaceWith(finalDiv);
} else if ($(".BOfSxb:contains("+ spanContent + ")").text() >= 1001 && $(".BOfSxb:contains("+ spanContent + ")").text() <= 1000000) {
$("span.BOfSxb:contains("+ spanContent + ")").replaceWith(finalDiv2);
} else {
//something else
}
EDIT: I should add this is actually a Chrome extension that will be doing the editing of the span elements on a page I have no control over.
Thank you for any help!
You can specify the element to grab by using it's index number in relation to it's class. You can do this with the jquery .eq() method.
$(".span.BOfSxb").eq(1).text();
$(".span.BOfSxb").eq(3).text();
You can then use the parseInt(); method to change them into numbers and add them if you wish. The parseInt() method returns an integer from a string. When you get the text from the elements they are not able to be added together because they are not considered numbers, they are considered text strings.
Here's the fiddle: http://jsfiddle.net/atw5z0ch/
If I understood your question, this should work:
HTML:
<span class="span">1234</span>
<span class="span">Other content 1</span>
<span class="span">1234</span>
<span class="span">Other content 2</span>
JavaScript (using jQuery):
var content = '1234';
// Notice:
// (i) content is a string. You should use quotes if you
// directly write the value, as specified here: https://api.jquery.com/contains-selector/
// (ii) Using classes to select objects with jQuery will return an array of elements
var spans = $('.span:contains(' + content + ')');
spans.each(function(i){
var value = parseInt($(this).text());
if(value > 0 && value < 1000){
console.log(value);
}
});
Working JsFiddle: http://jsfiddle.net/3tbag1qs/2/
UPDATE: as #zfrisch suggests, you can also get the spans by their positions. The solution presented here is another way to solve your problem, if you are not sure of the exact order.
You can use :nth-of-type selector. It probably wont work in older browsers though.
https://css-tricks.com/almanac/selectors/n/nth-of-type/
I got a HTML page with two div/class elements with the same name, called "notifications". However, I want to count only the latter ones and dont count the first one.
The first one looks like this:
<a href="mynotifcations"><div class="notification">1</div>
This one should be excluded.
The later ones look like this:
<div class="notiheader"><span class="notification">2 notifications</span>
Right now I get the notification like this
document.getElementsByClassName("notification");
If I cycle through it, it returns "1" and then "2 notifications".
I would rather get merely the "2 notifications", or better yet just the number 2 as an integer.
How do I manage to do achieve that? I'm really running out of ideas :/
I would have to say that is a strange setup, but here is a way:
<script>
var special = document.querySelectorAll( "span.notification" );
alert (special[1].innerHTML);
</script>
It might be better to add a class to distinguish them (that's what they're for), but if you must, you can use document.querySelectorAll() to match the specific ones you're looking for:
document.querySelectorAll("div .notification")
This will only match divs with the notification class.
var elementsWanted = document.querySelectorAll("div .notification");
for(var i = 0; i < elementsWanted.length; i++){
elementsWanted[i].style.backgroundColor = "yellow";
}
<div class="notification">Span</div>
<div class="notiheader"><span class="notification">Div</span>
<div class="notiheader"><span class="notification">Div</span>
<div class="notiheader"><span class="notification">Div</span>
<div class="notiheader"><span class="notification">Div</span>
Try this, here we first get all the notification classes, x.length gives the total no of notification classes in the html. Then do your stuff based on its index(zero based index).
function hookSecondNotification() {
var x = document.getElementsByClassName("notification")[1];
// x.style.backgroundColor = "red";
// here do your stuffs.
}
I have 3 divs
<div class="box opacity1 red"></div>
<div class="box opacity.5 green"></div>
<div class="box opacity0 blue"></div>
I want to have jQuery look at the page, see these classes and then create three different classes.
opacity1{
opacity: 1
}
opacity.5{
opacity: 0.5
}
opacity0{
opacity: 0
}
So when a user adds a class, eg "opacity75" to an element. I want the jQuery script to find "opacity" and then find what number is attached to it, then use that number to create a matching css class eg. opacity75{opacity:0.75}
I have very little knowledge of JS. I need some help to start me off in the right direction.
This can save having loads of CSS classes.
var stylestring = "<style type=\"text/css\">";
$("div").each(function() {
$.each($(this).attr("class").split(" "), function () {
var class = this + " {";
//add style to string
class += "}";
stylestring += class;
});
});
stylestring += "</style>";
$(document.body).prepend($(stylestring));
This would be my approach to iterate through all classes used in divs all over the page and create the class, but you would need some kind of rule to build the style out of the actual class name at the point of //add style to string
I'm not sure how it is even possible to create CSS classes in jQuery but here is a piece of code that'll do what you're expecting
Edit
$(function() {
$('.opacity').each(function() {
$(this).css('opacity', $(this).data('opacity'));
});
});
And add data-opacity="XX" to your <div> tags.
JSFiddle
1) yor example, its not best way to set css via js
2) i think task is to set some styles to elements, so its not necessarily to create classes.
jquery can set styles to elements via .css("property","value") method
3) example of code, which might work
// get all elements which contains 'opacity' in class name
var opacityElems = $( "div[class*='opacity']" );
var elemClassName;
var elemOpacityValue;
// cycle through all this elements
opacityElems.each(function(i,elem) {
// write the class name of the current element as a string
elemClassName = $(elem).attr('class');
// remove first 7 simbols, so only last numbers left
elemOpacityValue = elemClassName.substring(7, elemClassName.length);
// because obtained in the previous one step is a string, then give her number
// ie "0.12" to 0.12
elemOpacityValue *= 1;
// set style to element
$(elem).css("opacity",elemOpacityValue);
})
p.s. i am sorry for the mistakes - English is not the native language
I want to swap two html div tags entirely, tags and all. I tried the code below code but it does not work.
jQuery('#AllBlock-'+Id).insertAfter('#AllBlock-'+Id.next().next());
How to swap two div tags entirely.
You have some bracket mismatching in your code, it looks like you might be trying to do this:
jQuery('#AllBlock-'+Id).insertAfter($('#AllBlock-'+Id').next().next());
Which would take something like:
<div id="AllBlock-5"></div>
<div id="AllBlock-6"></div>
<div id="AllBlock-7"></div>
And, if called with Id 5, turn it into this:
<div id="AllBlock-6"></div>
<div id="AllBlock-7"></div>
<div id="AllBlock-5"></div>
This is because you're taking block 5, and moving it (using insertAfter) to the place after the block that's next().next() (or next-but-one) from itself, which would be block 7.
If you want to always swap #AllBlock-Id with #AllBlock-[Id+2], so they switch places and end up like the following:
<div id="AllBlock-7"></div>
<div id="AllBlock-6"></div>
<div id="AllBlock-5"></div>
You might want to try:
var $block = jQuery('#AllBlock-'+Id);
var $pivot = $block.next();
var $blockToSwap = $pivot.next();
$blockToSwap.insertBefore($pivot);
$block.insertAfter($pivot);
You can't do this because you can't concatenate a string and a jQuery object.
Try this:
var div = $('#AllBlock-'+Id);
div.insertAfter(div.next().next());
it should be like this
you should close the bracket after Id,
jQuery('#AllBlock-'+Id).insertAfter('#AllBlock-'+Id).next().next());
You'll need to detach the existing dom object first, then re-use it later:
$('#divid').detach().insertAfter('#someotherdivid');
What I understand is you want to swap a div when clicked with the last div. What will you do if it is the last div? move it to the top?
This solution should solve the problem, furthermore, you can modify this regex to match the format of your ID. This can probably be made more concise and robust. For example, you could get the last ID a bit more sophisticatedly. This may just be modifying the selector or something more. I mean, you do not want to go rearranging the footer or something just because its the last div on the page.
$('div').click(function() {
//set regex
var re = /(^\w+-)(\d+)$/i;
//get attr broken into parts
var str = $(this).attr('id').match(re)[1],
id = $(this).attr('id').match(re)[2];
//get div count and bulid last id
var lastStr = $('div:last').attr('id').match(re)[1],
lastID = $('div:last').attr('id').match(re)[2];
//if we have any div but the last, swap it with the end
if ( id !== lastID ) {
$(this).insertAfter('#'+lastStr+lastID);
}
//otherwise, move the last one to the top of the stack
else {
$(this).insertBefore('div:first');
} });
Check out this working fiddle: http://jsfiddle.net/sQYhD/
You may also be interested in the jquery-ui library: http://jqueryui.com/demos/sortable/