Wrap multiple div elements on same class - javascript

I would like to use jQuery to wrap sets of class elements in a div but can't find the solution.
HTML:
<div class="view-content">
<div class="first">content</div>
<div class="first">content</div>
<div class="second">content</div>
<div class="third">content</div>
<div class="third">content</div>
</div>
Desired Result:
<div class="view-content">
<div class="column">
<div class="first">content</div>
<div class="first">content</div>
</div>
<div class="column">
<div class="second">content</div>
</div>
<div class="column">
<div class="third">content</div>
<div class="third">content</div>
</div>
</div>

Demo http://jsfiddle.net/kQz4Z/8/
API: http://api.jquery.com/wrapAll/
Added a break line so that you can see the difference here :) http://jsfiddle.net/kQz4Z/10/
code
$(function() {
$('.first').wrapAll('<div class="column" />')
$('.second').wrapAll('<div class="column" />')
$('.third').wrapAll('<div class="column" />')
alert($('.view-content').html());
});​

Use wrapAll() method
$(function(){
var classes = ['.first', '.second', '.third'];
for (i = 0; i < classes.length; i++) {
$(classes[i]).wrapAll('<div class="column">');
}​
});
Demo: http://jsfiddle.net/g9G85/

Or here is the very short dynamical solution:
​$(".view-content > div").each(function() {
$(".view-content > ." + this.className).wrapAll("<div class='column' />");
});​
DEMO: http://jsfiddle.net/CqzWy/

You can use .wrap() to wrap something in a div but if your content is not ordered it will become a mess, here's an example:
Input
<div class="view-content">
<div class="first">content</div>
<div class="second">content</div>
<div class="first">content</div>
</div>
Output
<div class="view-content">
<div class="column">
<div class="first">content</div>
<div class="column">
<div class="second">content</div>
</div>
<div class="first">content</div>
</div>
</div>

You could try whit this:
var arr = $(".view-content div").map(function() { return $(this).attr('class'); }).get();
var results = $.unique(arr);
var i;
for(i = 0; i < results.length; i++){
$('.out').append('<div class="columns"></div>');
$('.'+results[i]).clone().appendTo('.columns:last');
}
alert($('.out').html());
Here an example:
JSFIDDLE

Related

How to get a index of class onhover?

I have the following div structure:
<div class="0">
<div class="test"></div>
</div>
<div class="1">
<div class="test"></div>
</div>
<div class="2">
<div class="test"></div>
</div>
<div class="3">
<div class="test"></div>
</div>
For example, if I hover on the 1st class: document.getElementbyClassName('test')[0], I should get index value is 0.
Edit: I'm looking for a pure JS solution
You can use the following code:
$('.test').mouseenter(function() {
console.log("index: " + $(this).index('.test'));
})
$('.test').mouseenter(function() {
console.log("index: " + $(this).index('.test'));
})
.test {
height: 100px;
width: 100px;
border: 1px solid blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
To do this in pure JS you can use querySelectorAll() to retrieve the target elements and bind a mouseenter event handler to them. Then you can find the index of the element which triggered the event by comparing it to the collection of children in the parent. Something like this:
let elements = document.querySelectorAll('.test');
elements.forEach(el => el.addEventListener('mouseenter', e => {
let index = Array.from(elements).indexOf(e.target);
console.log(index);
}));
<div class="1">
<div class="test">Test 1</div>
</div>
<div class="2">
<div class="test">Test 2</div>
</div>
<div class="3">
<div class="test">Test 3</div>
</div>
<div class="4">
<div class="test">Test 4</div>
</div>
This code Use pure java script :
var divItems = document.querySelectorAll(".test");
var mytab = [];
var index = 0;
for (let i = 0; i < divItems.length; i++) {
mytab.push(divItems[i].innerHTML);
}
for (var i = 0; i < divItems.length; i++)
{
divItems[i].onmouseover = function ()
{
index = mytab.indexOf(this.innerHTML);
console.log(this.innerHTML + " Index = " + index);
};
}
<div class="test">Hover me 1</div>
<div class="test">Hover me 2</div>
<div class="test">Hover me 3</div>
<div class="test">Hover me 4</div>

Could I get to an element using two ids?

Here's my code:
<div id='layer1'>
<div id='a'>
<div id='b'>
<div id='layer2'>
<div id='a'>
<div id='b'>
<div id='layer3'>
<div id='a'>
<div id='b'>
I want to try to get the element [a] of layer1.
Could I do this using pure javascript and withOUT jquery and other stuff?
An ID uniquely identifies one single element on the page. The behavior you described is more like "a class" inside of an ID:
document.querySelector("#counter-for-drinks .up-arrow")
and so if you want a different up-arrow, it is:
document.querySelector("#counter-for-burgers .up-arrow")
document.querySelector() is what is similar to jQuery $(" "). It also has the form document.querySelectorAll() for getting all matched elements.
Your HTML is missing closing tags. You can always validate your code here.
Also, you should use class instead of id.
<div id='layer1'>
<div class='a'></div>
<div class='b'></div>
</div>
<div id='layer2'>
<div class='a'></div>
<div class='b'></div>
</div>
<div id='layer3'>
<div class='a'></div>
<div class='b'></div>
</div>
You can use javascript to get elements:
document.querySelector("#layer1 .a")
var firstA = document.querySelectorAll('#layer1 #a');
var nodeString = '';
if (firstA.length > 0) {
for (var i = 0; i < firstA.length; i++) {
nodeString = nodeString + firstA[i].innerText + '<br/>';
}
}
document.getElementById('founded-nodes').innerHTML = nodeString;
#founded-nodes {
color: brown;
}
<div id='layer1'>
<div id='a'>layer1 aaa</div>
<div id='b'>layer1 bbb</div>
</div>
<div id='layer2'>
<div id='a'>layer2 aaa</div>
<div id='b'>layer2 bbb</div>
</div>
<div id='layer3'>
<div id='a'>layer3 aaa</div>
<div id='b'>layer3 bbb</div>
</div>
<div id="founded-nodes"></div>
As all said in above over comments and answers, one must use a single id on the same page, or else the use of classes is a must. But if you want to achieve this, you can have a look at code.

Remove div having particular name

From the code underneath, I want to remove the previous instances of codemirror, that is both "hello" and "hii" before I can add another instance.
The jQuery is not working.
Also, if I console.log($('#source').hasClass('.CodeMirror.cm-s-default')); it always shows me false, that is it can't find the classnames.
How can I do this?
If this is my html code:
<div class = "source" id="source" name="source">
<div class="result" id="result">
<div class="CodeMirror cm-s-default">hello</div>
<div class="CodeMirror cm-s-default">hii</div>
</div>
</div>
and my javascript, jquery is:
var first = document.getElementById("source").getElementsByClassName("CodeMirror cm-s-default");
var len1 = first.length;
for(var i = 0; i < len1; i++) {
if(first[i].className == "CodeMirror cm-s-default") {
first[i].parentNode.removeChild(first[i]);
}
}
you can do that to remove those elements contain .CodeMirror as a class:
javascript:
document.querySelectorAll(".CodeMirror").forEach(el => el.remove());
<div class="source" id="source" name="source">
<div class="result" id="result">
<div class="test">Not to remove</div>
<div class="CodeMirror cm-s-default">hello</div>
<div class="CodeMirror cm-s-default">hii</div>
</div>
</div>
Maybe simply like this?
$(function() {
$(".CodeMirror").remove();
});
Using jQuery can done like this:
$(".CodeMirror:contains('hello'), .CodeMirror:contains('hii')").remove()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="source" id="source" name="source">
<div class="result" id="result">
<div class="test">Not to remove</div>
<div class="CodeMirror cm-s-default">hello</div>
<div class="CodeMirror cm-s-default">hii</div>
</div>
</div>

Array sort before looping not keep the array sort

I have this code who simply create a array with html element and loop for parse the sort array.
$('document').ready(function(){
var arrElementStyle = [];
$('.bands-alphabetique [id*="band-style-"]').each(function(index){
var style = $(this).attr('id').split('-')[2];
arrElementStyle[style + '-' + index ] = $(this).find('.element');
});
arrElementStyle.sort();
$('.bands-alphabetique').hide();
for(style in arrElementStyle){
$('.large-centered.col-md-12.clearfix').append(arrElementStyle[style]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-centered col-md-12 clearfix">
<div class="bands-alphabetique">
<div class="col-md-3" id="band-style-rock">
<div class="element">
<h1 class="band-style-title">Rock</h1>
Fiction In Motion
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Pop</h1>
Marianas Trench
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Alternatif</h1>
Anberlin
</div>
</div>
</div>
</div>
When I parse the html the result is not sort?(I want sort by style of music) Why? Want should I do.
in your code you declared arrElementStyle as an array, but later you used it as an associative array for inserting data. So it is better to declare arrElementStyle as an object for this.
Here is an example demo of what I think you wanted to achieve with the help of sort() for sorting the objects keys:
$('document').ready(function() {
var arrElementStyle = {}; // declare arrEleemntStyle as object
$('.bands-alphabetique [id*="band-style-"]').each(function(index) {
var style = $(this).attr('id').split('-')[2];
// push into object of key <style>-<index> the elements
arrElementStyle[style + '-' + index] = $(this).find('.element');
});
// get the keys of arrElementStyle for sorting
var keys = Object.keys(arrElementStyle),
i, len = keys.length;
console.log('before = ', keys);
keys.sort(); // sort the object keys
console.log('after = ', keys);
$('.bands-alphabetique').hide();
// iterate the sorted keys and append it
for (i = 0; i < len; i++) {
var k = keys[i];
$('.large-centered.col-md-12.clearfix').append(arrElementStyle[k]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-centered col-md-12 clearfix">
<div class="bands-alphabetique">
<div class="col-md-3" id="band-style-rock">
<div class="element">
<h1 class="band-style-title">Rock</h1>
Fiction In Motion
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Pop</h1>
Marianas Trench
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Alternatif</h1>
Anberlin
</div>
</div>
</div>
</div>
Issue is you're trying to sort an object.. not an array. So let's use an object and sort it's keys.
$('document').ready(function() {
// here's the issue I was saying about
var elements = {};
$('.bands-alphabetique').hide().find('[id*="band-style-"]').each( function( index ) {
elements[ $(this).attr('id').split('-')[2] + '-' + index ] = $(this).find('.element');
});
var styles = Object.keys(elements);
styles.sort();
styles.forEach(function(style) {
$('.large-centered.col-md-12.clearfix').append(elements[style]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-centered col-md-12 clearfix">
<div class="bands-alphabetique">
<div class="col-md-3" id="band-style-rock">
<div class="element">
<h1 class="band-style-title">Rock</h1>
Fiction In Motion
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Alternatif</h1>
Anberlin
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Pop</h1>
Marianas Trench
</div>
</div>
</div>
</div>
The problem is that you're not sorting an array. You have an object with different properties (style + '-' + index).
In other words, associative array does not exists in Javascript. What you really had was an object arrElementStyle with many properties.
$('document').ready(function(){
var arrElementStyle = [];
$('.bands-alphabetique [id*="band-style-"]').each(function(index){
var style = $(this).attr('id').split('-')[2];
arrElementStyle[index] = $(this).find('.element');
arrElementStyle[index].bandStyle = $(this).find('.band-style-title')[0].innerHTML;
});
arrElementStyle.sort(function(elementA, elementB){
return elementA.bandStyle > elementB.bandStyle;
});
$('.bands-alphabetique').hide();
for(style in arrElementStyle){
$('.large-centered.col-md-12.clearfix').append(arrElementStyle[style]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-centered col-md-12 clearfix">
<div class="bands-alphabetique">
<div class="col-md-3" id="band-style-rock">
<div class="element">
<h1 class="band-style-title">Rock</h1>
Fiction In Motion
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Pop</h1>
Marianas Trench
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Alternatif</h1>
Anberlin
</div>
</div>
</div>
</div>

How to get this value in Javascript?

This is the HTML code:
<div id="CurrencyQuotePane">
<div class="CurrencyQuote">
<div class="column">
<div class="form-label">Pair: </div><div>1/2</div>
<div class="form-label padding-top">Spread: </div><div>385</div>
</div>
<div class="column">
<div class="form-label">Rate: </div><div>1/2</div>
<div class="form-label padding-top">High/Low: </div><div>2002.0/0.0055</div>
</div>
</div>
<div class="clear"></div>
</div>
How do I get the 385 in Javascript if it keeps changing?
This is my current javascript:
function getSpread(){
var tag = iframe.contentDocument.getElementByClassName('SPREAD');
var spread = Number(tag[1].innerHTML);
return spread;
}
Sorry if I don't know anything about javascript, I am a complete newbie.
Change it to this:
<div class="column">
<div class="form-label">Pair: </div><div>TEXT</div>
<div class="form-label padding-top">SPREAD</div><div id="spreadval">385</div>
</div>
function getSpread(){
var tag = iframe.contentDocument.getElementById('spreadval');
return parseInt(tag.innerHTML);
}
var column = document.getElementsByClassName('column');
var divs = column[0].getElementsByTagName('div');
alert(divs[1].innerHTML);
set id to your div
<div class="column">
<div class="form-label">Pair: </div><div>TEXT</div>
<div class="form-label padding-top">SPREAD</div><div id="changing_number">385</div>
</div>
get with jquery
$(function(){
var theNumber = parseInt($('#changing_number').text());
});
or with DOM:
$(function(){
var theNumber = parseInt(document.getElementById('changing_number').innerHTML);
});
here you can learn js: http://www.w3schools.com/jsref/met_doc_getelementbyid.asp

Categories

Resources