combine html paragraphs using javascript - javascript

I'm currently struggling on a very simple javascript task, but I'm new to it, so its confusing me a lot.
e.g. html
<div class="item">
<div class="title">Item 1 Title</div>
<div class="description-1">lorum</div>
<div class="description-2">ipsum</div>
<div class="description-combined"></div>
</div>
So I need to combine paragraphs 1 & 2, and replace the empty info in paragraph 3. I don't use jQuery yet, so my research has caused struggle because of this.... i currently have:
var p1 = getElementsByClassName ('description-1').innerHTML;
var p2 = getElementsByClassName ('description-2').innerHTML;
var p3 = p1 + P2
document.getElementsByClassName ('description-combined').innerHTML = p3
I did have p3 to have p1.concat(p2) but that didn't work. I'm using it as an external file, so i may be missing out on putting something in my HTML file too.

The edit changes the question.
What I'd probably do is loop through the .item elements, combining the descriptions within.
document.getElementsByClassName is a property of document, not a freestanding function, and it returns a list of matching elements. It's also not as widely supported as document.querySelector and document.querySelectorAll, so I'd probably use those; for what we're talking about, we'll also want Element#querySelector.
// Get a list of the items and loop through it
Array.prototype.forEach.call(document.querySelectorAll(".item"), function(item) {
// Get the two description divs, and the combined, that
// are *within* this item
var d1 = item.querySelector(".description-1");
var d2 = item.querySelector(".description-2");
var c = item.querySelector(".description-combined");
// Set the combined text (this assumes we have them all)
c.innerHTML = d1.innerHTML + d2.innerHTML;
});
.description-combined {
color: green;
}
<div class="item">
<div class="title">Item 1 Title</div>
<div class="description-1">One description 1</div>
<div class="description-2">One description 2</div>
<div class="description-combined"></div>
</div>
<div class="item">
<div class="title">Item 2 Title</div>
<div class="description-1">2 description 1</div>
<div class="description-2">2 description 2</div>
<div class="description-combined"></div>
</div>
<div class="item">
<div class="title">Item 3 Title</div>
<div class="description-1">3 description 1</div>
<div class="description-2">3 description 2</div>
<div class="description-combined"></div>
</div>
The Array.prototype.forEach.call(list, function() { ... }); thing is a way to loop through anything that's like an array, but isn't an array. It's explained more in this other answer, which also has several alternatives.

Related

Link simillary name classes so that when one is clicked the other is given a class

Basically, I'm asking for a way to optimize this code. I'd like to cut it down to a few lines because it does the same thing for every click bind.
$("#arch-of-triumph-button").click(function(){
$("#arch-of-triumph-info").addClass("active-info")
});
$("#romanian-athenaeum-button").click(function(){
$("#romanian-athenaeum-info").addClass("active-info")
});
$("#palace-of-parliament-button").click(function(){
$("#palace-of-parliament-info").addClass("active-info")
});
Is there a way to maybe store "arch-of-triumph", "romanian-athenaeum", "palace-of-parliament" into an array and pull them out into a click bind? I'm thinking some concatenation maybe?
$("+landmarkName+-button").click(function(){
$("+landmarkName+-info").addClass("active-info")
});
Is something like this even possible?
Thanks in advance for all your answers.
EDIT: Here's the full HTML.
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button"></div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button"></div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Assuming you're not able to modify your HTML markup (in which case with use of CSS classes would be cleaner), a solution to your question would be as shown below:
// Assign same click handler to all buttons
$("#arch-of-triumph-button, #romanian-athenaeum-button, #palace-of-parliament-button")
.click(function() {
// Extract id of clicked button
const id = $(this).attr("id");
// Obtain corresponding info selector from clicked button id by replacing
// last occurrence of "button" pattern with info.
const infoSelector = "#" + id.replace(/button$/gi, "info");
// Add active-info class to selected info element
$(infoSelector).addClass("active-info");
});
Because each .landmark-button looks to be in the same order as its related .landmark-info, you can put both collections into an array, and then when one is clicked, just find the element with the same index in the other array:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
This does not rely on IDs at all - feel free to completely remove those from your HTML to declutter, because they don't serve any purpose now that they aren't being used as selectors.
Live snippet:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
.active-info {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button">click</div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button">click</div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Older answer, without knowing the HTML: You can extract the ID of the clicked button, slice off the button part of it, and then select it concatenated with -info:
$(".landmark-button").click(function() {
const infoSel = this.id.slice(0, this.id.length - 6) + 'info';
$(infoSel).addClass('active-info');
});
A much more elegant solution would probably be possible given the HTML, though.

Random posts in javascript or php

I have 30 divs with different images and links and wanted to get them to be displayed in 10 different divs randomly.
Example: http://imgur.com/Ar1gdzL (it's an animated gif)
Something like a "random related posts" that we use in wordpress, but my page is not in wordpress. It's just a simple website in php.
 
the div would be so
Link
Link
Link
etc
etc
etc
How to do this in javascript or php?
Create 10 divs with those positions (empty divs)
Create a string array with the 10 (or more) html content that will fill the divs
Shuffle the array as stated here
Pass by the array and modify the innerHtml of the 10 divs one by one (Only first 10 elements since only 10 divs)
You can use different ways, depending on your needs. When using MySQL you can use a query like:
SELECT images, link FROM tablename WHERE ...... ORDER BY RAND()
Or you can use shuffle on an array.
$array = array ( 'image1', 'image2' );
shuffle ( $array );
// Display divs
<div class="divPool">content 1</div>
<div class="divPool">content 2</div>
<div class="divPool">content 3</div>
etc... to 30 divs
<div class="destination">destination 1</div>
<div class="destination">destination 2</div>
<div class="destination">destination 3</div>
etc. to 10 divs,
then in JavaScript:
//make arrays of the html elements in each class:
var arrayOfContent=document.getElementsByClassName("divPool");
var arrayOfDestinations=document.getElementsByClassName("destination");
for (var i=0; i<10: i++){//for each of the 10 destination divs
//select a random number from 0 to 29
var random=Math.floor(Math.random() * 30);
arrayOfDestinations[i].innerHTML=arrayOfContent[random].innerHTML
}
Also, in css you can make the divPool class invisible like this:
.divPool{display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
for(i=1;i<=10;i++){
var id = Math.floor(Math.random() * 30) + 1;
$("#display_"+id).show();
}
});
</script>
<div id="display_1" style="display:none;">1</div>
<div id="display_2" style="display:none;">2</div>
<div id="display_3" style="display:none;">3</div>
<div id="display_4" style="display:none;">4</div>
<div id="display_5" style="display:none;">5</div>
<div id="display_6" style="display:none;">6</div>
<div id="display_7" style="display:none;">7</div>
<div id="display_8" style="display:none;">8</div>
<div id="display_9" style="display:none;">9</div>
<div id="display_10" style="display:none;">10</div>
<div id="display_11" style="display:none;">11</div>
<div id="display_12" style="display:none;">12</div>
<div id="display_13" style="display:none;">13</div>
<div id="display_14" style="display:none;">14</div>
<div id="display_15" style="display:none;">15</div>
<div id="display_16" style="display:none;">16</div>
<div id="display_17" style="display:none;">17</div>
<div id="display_18" style="display:none;">18</div>
<div id="display_19" style="display:none;">19</div>
<div id="display_20" style="display:none;">20</div>
<div id="display_21" style="display:none;">21</div>
<div id="display_22" style="display:none;">22</div>
<div id="display_23" style="display:none;">23</div>
<div id="display_24" style="display:none;">24</div>
<div id="display_25" style="display:none;">25</div>
<div id="display_26" style="display:none;">26</div>
<div id="display_27" style="display:none;">27</div>
<div id="display_28" style="display:none;">28</div>
<div id="display_29" style="display:none;">29</div>
<div id="display_30" style="display:none;">30</div>
`

Reorder divs in javascript without jquery

lets say I have html:
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
how would I in javascript and not jquery reorder these divs to:
<div id="1">1</div>
<div id="3">3</div>
<div id="2">2</div>
You can use display:flex and the order css (I had to add a letter before the number for your id as SO didn't seem to like it for the css)
.container {display:flex; flex-direction:column}
#s1 {order:1;}
#s2 {order:3;}
#s3 {order:2;}
<div class="container">
<div id="s1">1</div>
<div id="s2">2</div>
<div id="s3">3</div>
</div>
More information about order
More information about flex
Update
Sorry read the question wrong - thought you wanted to do it without js
var div = document.getElementById('3')
div.parentNode.insertBefore(div, document.getElementById('2'))
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
The solution given by the duplicate questions are incorrect because they make the assumption that the elements are next to each other. But even in this simple example, there is a text node containing white-space between the elements.
Given that the two elements are not nested, you can use this to swap two elements:
function swapElements (first, second) {
var tmpNode = document.createElement('div');
tmpNode.setAttribute('id', '_tmp');
var firstParent = first.parentNode;
firstParent.insertBefore(tmpNode, first);
second.parentNode.insertBefore(second, first);
firstParent.insertBefore(second, tmpNode);
firstParent.removeChild(tmpNode);
}
Use it like:
var first = document.querySelector('#1');
var second = document.querySelector('#2');
swapElements(first, second);

Append a div to a new div

i am using IPB and i am going to put each category into a new tab the category div is something like this:
<div id='category_100'>
<div id='category_104'>
<div id='category_102'>
<div id='category_101'>
and my tabs content is like this:
<div class="content">
<div id="content-1" class="content-1">
</div>
</div>
and the categories divs is already showing but i want it to be moved to the content-1 div without duplicate so i want it to move from its div to this div with jjava script how?
<script>
document.getElementById('content-1').appendChild(
document.getElementById('category_100')
);
</script>
this worked for me but how can i add more than id to category_100
i want it to be like this in one script code so i would not repeart the scrip code four times:
<div class="content">
<div id="content-1" class="content-1">
<div id='category_100'>
<div id='category_104'>
<div id='category_102'>
<div id='category_101'>
</div>
</div>
using my two lines the suggested things here is not working!
Try this code :
$('div[id^="category_"]').appendTo('#content-1')
Have a look to this fiddle : http://jsfiddle.net/lulu3030/sjEPx/2/
"using my two lines the suggested things here is not working!"
You just get a single element with an ID and trying to append it...
Live Demo
If you want to append multiple elements, there are many ways...
Wrap those elements and then append...
<div id="categories">
<div id='category_100'></div>
<div id='category_104'></div>
<!-- etc. -->
</div>
document.getElementById('content-1').appendChild(document.getElementById('categories'));
or add same class to all elements that you want to append...
<div id='category_100' class="myClass"></div>
<div id='category_104' class="myClass"></div>
[].forEach.call(document.getElementsByClassName("myClass"), function (value, index, array) {
document.getElementById("content-1").appendChild(value);
});
or get elements with query selector that match some pattern...
[].forEach.call(document.querySelectorAll("div[id^='category_']"), function (value, index, array) {
document.getElementById("content-1").appendChild(value);
});
and etc.

How to wrap div around multiple of the same class elements

I'm trying to wrap multiple same class divs into a div and to skip divs not with the same class. .wrap doesn't combine them, and .wrapAll throws the non-classed divs underneath. I've been tinkering around with attempts to create an alternate solution but with no avail.
Original:
<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div>Skip in wrap</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
continued...
Wanted Result:
<div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
</div>
<div>Skip in wrap</div>
<div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
</div>
You can loop pretty quickly through your <div> elements using a for loop. In the below code, just change the initial selector here to grab all those siblings divs, e.g. #content > div.entry or wherever they are:
var divs = $("div.entry");
for(var i=0; i<divs.length;) {
i += divs.eq(i).nextUntil(':not(.entry)').andSelf().wrapAll('<div />').length;
}​
You can give it a try here. We're just looping through, the .entry <div> elements using .nextUntil() to get all the .entry elements until there is a non-.entry one using the :not() selector. Then we're taking those next elements, plus the one we started with (.andSelf()) and doing a .wrapAll() on that group. After they're wrapped, we're skipping ahead either that many elements in the loop.
I just whipped up a simple custom solution.
var i, wrap, wrap_number = 0;
$('div').each(function(){ //group entries into blocks "entry_wrap_#"
var div = $(this);
if (div.is('.entry')) {
wrap = 'entry_wrap_' + wrap_number;
div.addClass(wrap);
} else {
wrap_number++;
}
});
for (i = 0; i <= wrap_number; i++) { //wrap all blocks and remove class
wrap = 'entry_wrap_' + i;
$('.' + wrap).wrapAll('<div class="wrap"/>').removeClass(wrap);
}
You could alternatively append new divs to your markup, and then append the content you want wrapped into those.
If your markup is this:
<div class="wrap">
<div class="col-1"></div>
<div class="col-1"></div>
<div class="col-1"></div>
<div class="col-1"></div>
<div class="col-1"></div>
<div class="col-2"></div>
<div class="col-2"></div>
<div class="col-2"></div>
<div class="col-2"></div>
<div class="col-2"></div>
</div>
Use the following to append two new divs (column-one and column-two) and then append the appropriate content into those divs:
// Set vars for column content
var colOne = $('.col-1').nextUntil('.col-2').addBack();
var colTwo = $('.col-2').nextAll().addBack();
// Append new divs that will take the column content
$('.wrap').append('<div class="column-first group" /><div class="column-second ground" />');
// Append column content to new divs
$(colOne).appendTo('.column-first');
$(colTwo).appendTo('.column-second');
Demo here: http://codepen.io/zgreen/pen/FKvLH

Categories

Resources