Can I select classes by order like this? - javascript

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

Related

JavaScript possible to select all elements with classname that starts with (...)? [duplicate]

I'm trying to only show certain divs. The way I have decided to do this is to first hide all elements that start with "page" and then only show the correct divs. Here's my (simplified) code:
<form>
<input type="text" onfocus="showfields(1);">
<input type="text" onfocus="showfields(2);">
</form>
<div class="page1 row">Some content</div>
<div class="page1 row">Some content</div>
<div class="page2 row">Some content</div>
<div class="page2 row">Some content</div>
<script>
function showfields(page){
//hide all items that have a class starting with page*
var patt1 = /^page/;
var items = document.getElementsByClassName(patt1);
console.log(items);
for(var i = 0; i < items.length; i++){
items[i].style.display = "none";
}
//now show all items that have class 'page'+page
var item = document.getElementsByClassName('page' + page);
item.style.display = '';
}
</script>
When I console.log(items); I get a blank array. I'm pretty sure the regexp is right (get all items starting with 'page').
The code I'm using is old school JS, but I'm not adverse to using jQuery. Also if there is a solution that doesn't use regexp, that's fine too as I'm new to using regexp's.
getElementsByClassName only matches on classes, not bits of classes. You can't pass a regular expression to it (well, you can, but it will be type converted to a string, which is unhelpful).
The best approach is to use multiple classes…
<div class="page page1">
i.e. This div is a page, it is also a page1.
Then you can simply document.getElementsByClassName('page').
Failing that, you can look to querySelector and a substring matching attribute selector:
document.querySelectorAll("[class^=page]")
… but that will only work if pageSomething is the first listed class name in the class attribute.
document.querySelectorAll("[class*=page]")
… but that will match class attributes which mention "page" and not just those with classes which start with "page" (i.e. it will match class="not-page".
That said, you could use the last approach and then loop over .classList to confirm if the element should match.
var potentials = document.querySelectorAll("[class*=page]");
console.log(potentials.length);
elementLoop:
for (var i = 0; i < potentials.length; i++) {
var potential = potentials[i];
console.log(potential);
classLoop:
for (var j = 0; j < potential.classList.length; j++) {
if (potential.classList[j].match(/^page/)) {
console.log("yes");
potential.style.background = "green";
continue elementLoop;
}
}
console.log("no");
potential.style.background = "red";
}
<div class="page">Yes</div>
<div class="notpage">No</div>
<div class="some page">Yes</div>
<div class="pageXXX">Yes</div>
<div class="page1">Yes</div>
<div class="some">Unmatched entirely</div>
Previous answers contain parts of the correct one, but none really gives it.
To do this, you need to combine two selectors in a single query, using the comma , separator.
The first part would be [class^="page"], which will find all the elements whose class attribute begins with page, this selector is thus not viable for elements with multiple classes, but this can be fixed by [class*=" page"] which will find all the elements whose class attribute have somewhere the string " page" (note the space at the beginning).
By combining both selectors, we have our classStartsWith selector:
document.querySelectorAll('[class^="page"],[class*=" page"]')
.forEach(el => el.style.backgroundColor = "green");
<div class="page">Yes</div>
<div class="notpage">No</div>
<div class="some page">Yes</div>
<div class="pageXXX">Yes</div>
<div class="page1">Yes</div>
<div class="some">Unmatched entirely</div>
You can use jQuery solution..
var $divs = $('div[class^="page"]');
This will get all the divs which start with classname page
$(document).ready(function () {
$("[class^=page]").show();
$("[class^=page]").hide();
});
Use this to show hide div's with specific css class it will show/hide all div's with css class mention.

Get part of CSS class as string?

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

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

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

How to get parent id of an anchor tag using prototype?

Event.observe(window, 'load',
function() {
$$('a.tag_links').each(function(s) {
//alert(s.parent.parent.id); //How to get id of its parent to parent
});
}
);
I want to get the id of the parent element.
Structure is something like this.
<div class="home-page" id='entity-1'>
<div class="index-page-category">
food
</div>
Result should be entity-1
Like this:
$$('a.tag_links').each(function(s) {
var parentid = $(s).up('div').id;
});
First, your HTML is incomplete. Does it look like:
<div class="home-page" id='entity-1'>
<div class="index-page-category"></div>
food
</div>
Or like this:
<div class="home-page" id='entity-1'>
<div class="index-page-category">
food
</div>
</div>
Either way, you should be able to achieve this by using:
$$('a.tag_links').each(function(s) {
var divId = $(s).previous('div.home-page').id;
});
I imagine the reason you're iterating through 'a.tag_links' is that you have a bunch of links? Based on that context, is that HTML structure always consistent (the outter div will always contain a class of 'home-page')?

Categories

Resources