JS - combining array items together in one item - javascript

For example I want to collect some tags (lets say paragraph):
var tagsCollection = document.getElementsByTagName('p');
var tagsCollectionLength = tagsCollection.length
I loop through (iterate):
for (var i = 0; i < tagsCollectionLength; i++)
{
//get an array:
var tagsCollectionArray = tagsCollection[i];
}
Now what to do to get all array items as ONE item:
so it won't looks like:
[paragraph1, paragraph2, paragraph3]
but like:
[paragraph1paragraph2paragraph3]
I did try join. concat. etc. without success probably I'm doing something wrong, any help is appreciated. Thanks.

you can keep a variable outside the for, append the strings inside for and when for finishes, push it inside an array.
Here's how to do that -
var tagsCollection = document.getElementsByTagName('p');
var tagsCollectionLength = tagsCollection.length;
var tags = "", tagsCollectionArray = [];
for (var i = 0; i < tagsCollectionLength; i++)
{
tags = tags + tagsCollection[i];
}
tagsCollectionArray.push(tags);

Suppose you have this html
<div>
<p>a</p>
<p>b</p>
<p>c</p>
<p>d</p>
<p>e</p>
</div>
Assuming the result you want is an Array of all the paragraphs's content ([paragraph1paragraph2paragraph3]), then you could do the following:
tagsCollection = document.getElementsByTagName('p');
var ar = [];
for(var i = 0; i < tagsCollection.length; i++ ) {
ar.push(tagsCollection[i].innerText)
}
console.log([ar.join('')]) // => ["abcde"]
See this fiddle

As I have already commented, you can use Array.join("").
JSFiddle.
(function() {
var data = [];
var str = [].map.call(document.getElementsByTagName('p'), function(item) {
return item.innerHTML;
}).join("");
data.push(str);
document.write("<pre>" + JSON.stringify(data) + "</pre>");
})()
<p>hello</p>
<p>workd</p>
<p>test</p>

Related

Inserting array to "replace" function but it inserts the array in different order

I have a JavaScript function that does a couple of things:
gets the selected values from different select forms and adds them to an array. This works ok since it stores the values in the correct order.
I have const that is actually an HTML template where I need to insert the selected values in the order of the array. This is where I have my problem.
When I insert the array it seems that it inserts the values randomly and I don't know how to fix it.
This is my js function
function cambiarImagen(){
var elements = document.getElementsByClassName('custom-select img');
var seleccionPath = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var strSel = element.options[element.selectedIndex].text;
seleccionPath.push(strSel);
} console.log(seleccionPath);
let index = 0;
const html = `<!DOCTYPE html>
<html>
<head>
<title>Escenario Virtual de Imagenes</title>
<script src="js/aframe.min.js"></script>
<script>
//variables de estimulos dentro del arreglo de secuencias//
var neutro='img/negro.png';
var instruccionesImagenes='img/Imagenes_instrucciones.png';
var imagen1='img/1.jpg';
var imagen2='img/2.jpg';
var imagen3='img/3.jpg';
var imagen4='img/4.jpg';
var imagen5='img/5.jpg';
</script>
</head>
<body>
</body>
</html>`;
let result = html;
const re = /var imagen.*='(.*)';/gm;
while ((m = re.exec(html)) !== null) {
result = result.replace(m[1], seleccionPath[index]);
index++;
}
console.log(result);
}
The problem must be in the while loop because the array shows in the correct order when I console.log the array before I send it to the function.
I'll show one example of my outputs.
Array before using the while loop:
Array(5) [ "img/2.jpg", "img/5.jpg", "img/4.jpg", "img/1.jpg", "img/3.jpg" ]
The output of the replace:
var imagen1='img/3.jpg';
var imagen2='img/2.jpg';
var imagen3='img/1.jpg';
var imagen4='img/4.jpg';
var imagen5='img/5.jpg';
result = result.replace(m[1], seleccionPath[index]);
The problem lies in the fact that we are naively replacing the regex result substring and not considering whether it may exist more than once in result.
For the specific replacements and the HTML we are using, [ "img/2.jpg", "img/5.jpg", "img/4.jpg", "img/1.jpg", "img/3.jpg" ], after one loop, we end up with:
var imagen1='img/2.jpg';
var imagen2='img/2.jpg';
var imagen3='img/3.jpg';
var imagen4='img/4.jpg';
var imagen5='img/5.jpg';
Here we can see that "img/2.jpg" now exists twice in result, thus the next replacement ("img/2.jpg" with "img/5.jpg") occurs on the first line because for String.prototype.replace only the first occurence will be replaced, resulting in:
var imagen1='img/5.jpg';
var imagen2='img/2.jpg';
var imagen3='img/3.jpg';
var imagen4='img/4.jpg';
var imagen5='img/5.jpg';
This happens a number of times with this data set, 4 ends up in the right place (3rd slot) but then is replaced by 1 (which is supposed to end up where 4 is originally), essentially we are not taking into consideration that the matches to the regex may be inserted into the result.
One way to do it is to replace the while loop by a call to String.replace() with a function as parameter:
result = result.replace(re, (m, p1) => {
return m.replace(m, seleccionPath[index++]);
});
The function is called for each match in the order they are found. For each one, the contents of the first capture group (p1, which contains 'img/n.jpg') is replaced by whatever's in seleccionPath at the current index.
function cambiarImagen() {
const elements = document.getElementsByClassName('custom-select img');
let seleccionPath = [];
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
const strSel = element.options[element.selectedIndex].text;
seleccionPath.push(strSel);
}
console.log(seleccionPath);
let index = 0;
const html = `
...
let imagen1='img/1.jpg';
let imagen2='img/2.jpg';
let imagen3='img/3.jpg';
let imagen4='img/4.jpg';
let imagen5='img/5.jpg';
...
`;
let result = html;
const re = /let imagen.*='(.*)';/gm;
result = result.replace(re, (m, p1) => {
return m.replace(p1, seleccionPath[index++]);
});
console.log(result);
}
cambiarImagen();
<select class="custom-select img">
<option>img/2.jpg</option>
</select>
<select class="custom-select img">
<option>img/5.jpg</option>
</select>
<select class="custom-select img">
<option>img/4.jpg</option>
</select>
<select class="custom-select img">
<option>img/1.jpg</option>
</select>
<select class="custom-select img">
<option>img/3.jpg</option>
</select>
I think you can use this line of code:
function cambiarImagen(){
var elements = document.getElementsByClassName('custom-select img');
var seleccionPath = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var strSel = element.options[element.selectedIndex].text;
seleccionPath.push(strSel);
} console.log(seleccionPath);
// changses begin from here
var index = 1;
var html = `<html>
<head>
<title>Escenario Virtual de Imagenes</title>
<script src='js/aframe.min.js'></script>
<script>
//variables de estimulos dentro del arreglo de secuencias//
var neutro='img/negro.png';
var instruccionesImagenes='img/Imagenes_instrucciones.png';<br />`;
for (var i = 0; i < seleccionPath.length; i++) {
html = html + "var imagen" + index + "='" + seleccionPath[i] + "';<br />";
index++;
}
html += `
</script >
</head >
<body></body>
</html >`;
let result = html;
console.log(result);
}
the output in the html is:
var imagen1='img/2.jpg';
var imagen2='img/5.jpg';
var imagen3='img/4.jpg';
var imagen4='img/1.jpg';
var imagen5='img/3.jpg';
good luck.

Need to remove hyphen in the array

I have an array with some elements in it.
var arr=["bet-vet","ban-van","baskat-vase"];
While displaying the array, the want the hyphen in between the words to be removed. When it is being displayed,
the user should see
Bet,vet,ban,van,baskat,vase
Here is the link of my code
You ca try:
var arr = ["bet-vet", "ban-van", "baskat-vase"];
arr= arr.join("-").split("-").join();
console.log(arr);
Use Javascript Joint() & Split() method
example:
var arr=["bet-vet","ban-van","baskat-vase"];
var arrJoin = arr.join("-");
var arrsplit = arrJoin.split("-");
console.log(arrsplit);
You can try this
<script>
var b_or_v =["bet-vet","bat-vat","reb-rev","bick-vic","ban-van"];
function removeHyphen()
{
var newArray = [];
for(i=0;i<b_or_v.length;i++)
{
res = b_or_v[i].split("-");
newArray.push(res[0]);
newArray.push(res[1]);
}
console.log(newArray);
document.getElementById("text").innerHTML = newArray;
}
</script>
<body>
<button onclick="removeHyphen()">Find Val</button>
<div id="text">
</div>
</body>
Here is jsFiddle link
Try to use code as mentioned below:
document.getElementById("btn-1").onclick= function(){
document.getElementById("submit").onclick= function(){
var txt = [];
for (var i = 0; i < b_or_v.length; i++) {
if(b_or_v[i].match(/-/g)){
txt += b_or_v[i].split('-');
txt += ', ';
}
else{
txt += b_or_v[i]+', ';
}
}
Output: b_or_v : bet, vet, bat, vat, reb, rev, bick, vic, ban, van,
What about something like this:
var arr = ["bet-vet", "ban-van", "baskat-vase"];
var arr1 = [];
for(var i= 0; i < arr.length;i++){
test= arr[i].replace('-', '');
arr1.push(test);
}
console.log(arr1.join(', '));

How to select all elements of the same class before

I have something like this:
<div class="htx">
<div>string</div>
</div>
<div class="htx">
<div>string</div>
</div>
<div class="htx">
<div>otherString</div>
</div>
<div class="htx">
<div>string</div>
</div>
I want to select all htx class elements before that one which contains otherString
var res = $('.htx:contains("otherString")');
var sec = res.prevAll();
This didn't work.
You can use:
var res = $('.htx:contains("otherString")');
var sec = res.prevAll('.htx');
jsfiddle (with the exact code from the question + console.log)
Works as expected, the console.log(sec.toArray()); shows 2 divs you are looking for
Like that,
var res = $('.htx div:contains(otherString)');
var sec = res.prevAll();
Using pure JavaScript you can do this:
Demo on Fiddle
var all = document.getElementsByClassName('htx');
for (i = 0; i < all.length; i++) {
if (all[i].getElementsByTagName('div')[0].innerHTML == 'otherString') {
break
} else {
all[i].style.backgroundColor = 'sienna';
}
}
try this in jquery:
var l = $(".htx").lenght;
var elements ="";
for(var i=i; i<=l; i++)
{
if($(".htx:nth-child('" + i + "')").children("div").text() == "otherString")
break;
else
elements += $(".htx:nth-child('+i+')");
}
Hope this helps.

How to replace all the text in the text in a loop?

Sorry for my english =)
I need to replace some of the elements on a page. Here is my code:
var text1 = $('body').html().replace(/text1/, 'text11');
var text2 = $('body').html().replace(/text2/, 'text22');
var text3 = $('body').html().replace(/text3/, 'text33');
array = [text1, text2, text3];
for (var i = 0; i < array.length; i++) {
$('body').html(array[i])
};
But to replace only the first and third, if you remove the third element array, first and second is changed. Please tell me how to do it. Thank you!
var items = [
{ find: /text1/, replace: 'text11' },
{ find: /text2/, replace: 'text22' },
{ find: /text3/, replace: 'text33' }
];
var text = $('body').html();
for (var i = 0; i < items.length; i++)
{
var item = items[i];
text = text.replace(item.find, item.replace);
}
$('body').html(text);
That's because the original body html remains unchanged when the variables are evaluated. You would need to chain the replaces or use the previous variables for another replaces:
var text1 = $('body').html().replace(/text1/, 'text11');
var text2 = text1.replace(/text2/, 'text22');
var text3 = text2.replace(/text3/, 'text33');
And then you don't need any iterations..
$('body').html(text3);

How to point elements childrens with JavaScript

I have little problem with element childrens.
Heres some code to explain my question:
function check(element){
// I want to get custom attribute from element children.
// Children elements are always radio buttons
var temp = element. ?? .attr('temp');
return temp;
}
// element variable is the whole div here
<div id = "test">
<table>
<tr>
<td> <input type="radio" temp="somethinghere"/></td>
</tr>
</table>
</div>
Hope someone has ideas or even better.. solution.
I think you want something like this:
function check(element) {
var ret = [];
for (var i = 0; i < element.childNodes.length; i++) {
if (element.childNodes[i].type == 'radio') {
ret.push(element.childNodes[i].getAttribute('temp'));
}
}
return ret;
}
This will return an array containing all the temp attributes of the radio children of the element.
var temp = element.getAttribute('temp')
Or
var temp = element.temp = temp;
Or
var temp = element['temp'] = temp;
https://developer.mozilla.org/en/DOM/element.getAttribute
Edit: try:
var temp = '';
for (var i = 0; i < element.childNodes; i++)
temp += element.childNodes[i].getAttribute('temp');
return temp;
Is this what you're looking for?
To get an array of all the children of element :
element.childNodes;
To get an array of all input tags that are descendants of element :
element.getElementsByTagName("input")
Then loop through either of those arrays.
try this for the first child radio button
var temp = element.children(':radio:first').attr('temp');
of if you want all 'temp' attr from all child radio button do following:
var arrTemp = element.children(':radio').map(function(){
return $(this).attr('temp');
// or you can make it more detail like:
// return { ID: $(this).attr('id'), Temp: $(this).attr('temp') };
}).get();
UPDATE for table sample
var arrTemp = element.find(':radio').map(function(){
return $(this).attr('temp');
// or you can make it more detail like:
// return { ID: $(this).attr('id'), Temp: $(this).attr('temp') };
}).get();

Categories

Resources