Get part of CSS class as string? - javascript

Say I had the following 4 divs:
<div class="mine-banana"></div>
<div class="mine-grape"></div>
<div class="mine-apple"></div>
<div class="orange"></div>
I've discovered I can use the following JQuery selector to get the 3 "mine" divs, but I can't quite figure out how to return all the fruits that are "mine" :)
$('[class*=" mine-"]').each(function() {
var fruit = $(this).????
});

DEMO
The best way to accomplish that is to refactor your html, as #Ian pointed it out, for example :
<div class="mine" data-mine-fruit="banana"></div>
<div class="mine" data-mine-fruit="grape"></div>
<div class="mine" data-mine-fruit="apple"></div>
<div class="orange"></div>
The JS code is straightforward now :
var fruits = $('.mine').map(function () {
return $(this).attr('data-mine-fruit')
});
If you still want to use your current code, here is a regex-based code
var fruits = []
$('[class*=" mine-"], [class^="mine-"]').each(function() {
fruits.push( this.className.match(/[^a-z0-9_-]?mine-([0-9a-z_-]+)/i)[1] );
})
which really works

Related

Can I select classes by order like this?

So I have this HTML here generated by Wordpress. I want to select the DIVs seperately using JS. Is this possible? Can I maybe select them by the order on which JS finds them in my HTML?
I tried if something like this would be possible (By adding an index number) but I believe that is used only for the LI element. But you get the idea. The end result is to add a different classname to each div object using .className
var koffie = document.getElementsByClassName("g-gridstatistic-item-text2")[0];
var brain = document.getElementsByClassName("g-gridstatistic-item-text2")[1];
var tevred = document.getElementsByClassName("g-gridstatistic-item-text2")[2];
console.log(koffie);
console.log(brain);
console.log(tevred);
<div class="g-gridstatistic-wrapper g-gridstatistic-3cols">
<div class="g-gridstatistic-item">
<div class="g-gridstatistic-item-wrapper">
<div class="g-gridstatistic-item-text1 odometer" data-odometer-value="4"></div>
<div class="g-gridstatistic-item-text2">Kopjes koffie per dag</div>
</div>
</div>
<div class="g-gridstatistic-item">
<div class="g-gridstatistic-item-wrapper">
<div class="g-gridstatistic-item-text1 odometer" data-odometer-value="14"></div>
<div class="g-gridstatistic-item-text2">Brainstormsessies per week</div>
</div>
</div>
<div class="g-gridstatistic-item">
<div class="g-gridstatistic-item-wrapper">
<div class="g-gridstatistic-item-text1 odometer" data-odometer-value="12"></div>
<div class="g-gridstatistic-item-text2">Tevreden klanten</div>
</div>
Your JavaScript code is looking for DOM elements before it checks whether the DOM has even loaded. Try wrapping it in an event listener, like so:
JS
document.addEventListener('DOMContentLoaded', function () {
var koffie = document.getElementsByClassName("g-gridstatistic-item-text2")[0];
var brain = document.getElementsByClassName("g-gridstatistic-item-text2")[1];
var tevred = document.getElementsByClassName("g-gridstatistic-item-text2")[2];
//console.log(koffie);
//console.log(brain);
//console.log(tevred);
/* to evidence that targeting works: */
brain.classList.add('addedClass');
});
CSS
.addedClass {
font-size:22px;
color:red;
}
Full demo here:
https://jsbin.com/saxizeyabo/edit?html,css,js,console,output
simply like this
var yourVariableName = document.getElementsByClassName("g-gridstatistic-item-text2");
console.log(youVariableName[0]);
console.log(youVariableName[1]);
and so on like an array
document.querySelectorAll('.g-gridstatistic-item-text2').item(0);
https://developer.mozilla.org/de/docs/Web/API/Document/querySelectorAll
This way, you can just use CSS-Selectors
The below code should work.
var classes = document.getElementsByClassName('g-gridstatistic-item-text2');
for(var i=0; i<=classes.length; i++) {
var appendClass = 'your_class_name'+i;
classes[i].classList.add(appendClass);
}

Combining multiple similar functions into one

I've searched through StackOverflow for what I regard as a basic issue, but I could not find any relevant threads. Mainly because I feel like I am searching for the wrong keywords.
I would like to know how the summarize the next bit into as few lines of code as possible. When you click on 'link-#', it loads the content from the hidden div 'more-#' (where the # in more could be any number, but is the same as the number in link-#.) Right now I have this:
jQuery("#link-1").click(function(){
jQuery('#more').hide().html($('#more-1').html()).fadeIn(400)
});
jQuery("#link-2").click(function(){
jQuery('#more').hide().html($('#more-2').html()).fadeIn(400)
});
jQuery("#link-3").click(function(){
jQuery('#more').hide().html($('#more-3').html()).fadeIn(400)
});
etc.
I assume it should be something like below, but obviously it's not the correct way.
jQuery("#link" + NUMBER ).click(function(){
jQuery('#more').hide().html($('#more-' + this.NUMBER).html()).fadeIn(400)
});
I bet you guys know exactly how to deal with this! Thank you for your help.
Best regards,
Thomas
A preferable approach is to group these items by giving them the same class, and use a data-* attribute to identify the associated element:
jQuery(function() {
jQuery(".show-more").click(function() {
var target = $(this).data('target');
jQuery('#more').hide().html($(target).html()).fadeIn(400);
});
});
#moreItems {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
Show More 1
Show More 2
Show More 3
<div id="more"></div>
<div id="moreItems">
<div id="more-1">Here are the details 1</div>
<div id="more-2">Here are the details 2</div>
<div id="more-3">Here are the details 3</div>
</div>
Give them all the same class name and then add the attribute "data-num" and then:
jQuery(".className").click(function () {
var $this = $(this);
var html = jQuery('#more' + $this.attr('data-num')).html();
jQuery('#more').hide().html(html);
});
Example HTML:
<a class='className' data-num='1'>Link</a>
<div id='more1'></div>
<div id='more'></div>

Remove from Parent DIV container

i have got this :
<div id="video_pattern">
<div id="des"position:relative;></div>
<div id="mes"position:relative;></div>
</div>
i want to remove the
> <div id="video_pattern">
but the
<div id="des"position:relative;></div>
<div id="mes"position:relative;></div>
should stay, is this possible?
To handle your exact situation you can use this code:
var ToRemoveElement = document.getElementById("video_pattern");
ToRemoveElement.parentNode.appendChild(document.getElementById("des"));
ToRemoveElement.parentNode.appendChild(document.getElementById("mes"));
ToRemoveElement.remove();
This is the way to go if you only want these specific elements removed from the video_pattern div. If you want a more generic solution to remove all child elements then use the following:
var ToRemoveElement = document.getElementById("video_pattern");
var children = ToRemoveElement.children;
while (children.length > 0) {
ToRemoveElement.parentNode.appendChild(children[0]);
}
ToRemoveElement.remove();
JSfiddle example
Using Jquery you can do like this
var inner = $("#video_pattern").contents();
$("#video_pattern").replaceWith(inner);

loop the .append() with selector as variable

I am trying to loop the .append() function in order to change the selector each time with different value. But, I don't know the syntax for the selector in order to meet my target. So, how to change it? Thanks so much!
Ka Ho
<script type="text/javascript">
var a=3;
for (var i=0;i<a;i++) {
$i.append(i);
}
</script>
<div class="0"></div> // expected: display 0
<div class="1"></div> // expected: display 1
<div class="2"></div> // expected: display 2
You can also use a function as argument to append, might be cleaner and possibly faster in your case:
$('div').append(function() {
return this.className;
});
http://jsfiddle.net/sSVL8/
<script type="text/javascript">
var a=3;
for (var i=0;i<a;i++) {
$("."+i).append(i); //this is what you need
}
</script>
<div class="0"></div> // expected: display 0
<div class="1"></div> // expected: display 1
<div class="2"></div> // expected: display 2
First of all numeric class and ids are not supported that much as you think it is.
Update your HTML to something like this
<div class="box-0"></div>
<div class="box-1"></div>
<div class="box-2"></div>
Then you can use the script provided by deadlock in his answer.
var a=3;
for (var i=0;i<a;i++) {
$(".box-"+i).append(i); //this is what you need
}

How to implement multiple tinyscrollbars from a class?

I'm trying to implement multiple scrollbars with the plugin Tinyscrollabr.js
http://baijs.nl/tinyscrollbar/
To implement the scrollbars, i use a function scrollify like in this article :
http://www.eccesignum.org/blog/making-tinyscrollbarjs-easier-to-implement
HTML :
<ul id="myList">
<li id="scrollbar1" class="col">
<h2>Title 01</h2>
<div class="scrollBox"><!--Scrollable Content here--></div>
</li>
<li id="scrollbar2 class="col">
<h2>Title 02</h2>
<div class="scrollBox"><!--Scrollable Content here--></div>
</li>
<li id="scrollbar3 class="col">
<h2>Title 03</h2>
<div class="scrollBox"><!--Scrollable Content here--></div>
</li>
</ul>
Javascript :
function scrollify(element,options) { // '#element', {list:of,key:values}
var opt = options || {}
$(element).children().wrapAll('<div class="viewport"><div class="overview"></div></div>');
$(element).prepend('<div class="scrollbar"><div class="track"><div class="thumb"><div class="end"></div></div></div></div>');
$(element).tinyscrollbar(options);}
$scrollbar1 = $('#scrollbar1 .scrollBox') ;
$scrollbar2 = $('#scrollbar2 .scrollBox');
$scrollbar3 = $('#scrollbar3 .scrollBox');
$scrollbar4 = $('#scrollbar4 .scrollBox');
$(function() {
scrollify($scrollbar1);
scrollify($scrollbar2);
scrollify($scrollbar3);
scrollify($scrollbar4);
})
I would to make this more simple.
For example, i would to be able to make this :
$(function() {
scrollify('.scrollBox');
})
But tinyscrollbar need an id. With a class, it's load the first scrollbar and not the others. Firebug return this error message "f.obj[0] is undefined"
Sorry if my question is stupid, but how can I do for applying tinyscrollbar to a list of elements with a class ?
And then, after some actions how to update all this scrollbars with the function $allScrollbars.tinyscrollbar_update();
Thanks for help, I'm just beginning with javascript and i'm trying to learn.
I would count the number of elements with the class:
var scrollCount = $(".scrollbox").size();
Then use an iterating loop to call each of your IDs:
for (i=0; i<5; i++) {
scrollify($('#scrollbar' + i));
}
Also I would recommend using DIVs instead of the list setup you have, use the example from the link you shared as a starting point :)
Thanks KneeSkrap3r for your answer. It's a good solution to make this but i'm trying to do something in the case i' don't know the numbers of element to scroll.
I think I've found with something like this (it's a part from the first jquery plugin i'm trying to do ) where $el is all elemnts with the class"scrollbox".
$el.each(function(index)
{
var $scrolls = $(this);
function scrollify(element,options)
{ // '#element', {list:of,key:values}
var opt = options || {}
$(element).children().wrapAll('<div class="viewport"><div class="overview"></div></div>');
$(element).prepend('<div class="scrollbar"><div class="track"><div class="thumb"><div class="end"></div></div></div></div>');
$(element).tinyscrollbar(options);
}
scrollify($scrolls);
// Update heights
$(window).resize(function()
{ $scrolls.tinyscrollbar_update('relative');
});
})
Like this, it's seems to work but i don't know if i'm using good practice of javascript.
For the Html markup, I told the li elements for div, it's better for the semantic.
Thanks for tips ;-)

Categories

Resources