Copy Class Values to Div - javascript

I have HTML File:
<div class="um-field-area">
<div class="um-field-value">Value1</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value2</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value3</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value4</div>
</div>
<button onclick="Function()">Whatever</button>
<div id="result"></div>
I'd like my function to take values from all four divs with class "um-field-value"
<div class="um-field-value">Value1</div>
And past them in Div "result"
Essentially, I want a script to simply copy values given in class um-field-value and paste it in a "result" div. I tried following:
function Function() {
var x = document.getElementsByClassName("um-field-value");
document.getElementsById('result').innerHTML = x;
}
But that doesn't work at all.
I am somewhat new to coding so I am not entirely sure if it is even possible. Googled for over an hour but couldn't find any solutions.

document.getElementsByClassName gets the HTML nodes themselves but then you have to extract the values from within the HTML nodes, combine them, and set that to your result div. Example snippet below:
function myFunction() {
var valueNodes = Array.prototype.slice.call(document.getElementsByClassName("um-field-value"));
var values = valueNodes.map(valueNode => valueNode.innerHTML);
var result = values.join(' ');
document.getElementById('result').innerHTML = result;
}
<div class="um-field-area">
<div class="um-field-value">Value1</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value2</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value3</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value4</div>
</div>
<button onclick="myFunction()">Whatever</button>
<div id="result"></div>

Use querySelectorAll to get all the dom with this class um-field-value and iterate over that to get the innerHTML
There is a typo in your code.It is getElementById instead of getElementsById. There is an extra s
function Function() {
var x = document.querySelectorAll(".um-field-value");
let result = '';
for (var y = 0; y < x.length; y++) {
result += x[y].innerHTML;
}
document.getElementById('result').innerHTML = result;
}
<div class="um-field-area">
<div class="um-field-value">Value1</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value2</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value3</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value4</div>
</div>
<button onclick="Function()">Whatever</button>
<div id="result"></div>

You are on the right track. document.getElementsByClassName will return a NodeList. You need to get the innerText for each of the elements in that list. Depending on the browser you can either use forEach or a regular for loop to iterate over the list.
function Function() {
var fieldsList = document.getElementsByClassName("um-field-value");
var fieldValues = [];
fieldsList.forEach(function(field) { fieldValues.push(field.innerText) });
document.getElementsById('result').innerHTML = fieldValues.join(", ");
}

This is a simple and readable solution that uses a loop to get the text inside each element and add it to a string. getElementsByClassName returns an array of all elements found, so a loop is needed to get the text inside each with textContent.
function Function() {
var result = '';
var fields = document.getElementsByClassName("um-field-value");
for (var i=0; i<fields.length; i++) {
result += fields[i].textContent + '\n';
}
document.getElementById('result').innerHTML = result;
}
<div class="um-field-area">
<div class="um-field-value">Value1</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value2</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value3</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value4</div>
</div>
<button onclick="Function()">Whatever</button>
<div id="result"></div>

Related

Get values from ID HTML and save in array

I'm doing a view where once I click I'm displaying
For Loop
I am having a view that captures a QR code and displays it on the screen, what I want to do next is take these values by iterating the elements with a for loop and save it in an array, in this case my ID is id="scanned-result" and I want to iterate each containing values and saving to an array.
I am doing this but for some reason it is not performing the operation correctly. I would like to know what I should correct?
function SubmitCodes() {
var QRCodeval= document.querySelectorAll('scanned-result');
var arr = [];
for (var i in QRCodeval) {
alert(QRCodeval[i]);
arr.push( QRCodeval[i]);
}
alert(arr.val);
}
VIEW
<div class="container">
<div class="row">
<div class="col-md-12" style="text-align: center;margin-bottom: 20px;">
<div id="reader" style="display: inline-block;"></div>
<div class="empty"></div>
<div id="scanned-result">
<div>[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp</div>
<div>[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0</div></div>
</div>
</div>
</div>
There are several issues with your code. To select element by ID using querySelector you need to use # selector, also to select the divs inside you can use element > element selector.
var QRCodeval = document.querySelectorAll("#scanned-result>div");
querySelectorAll returns a nodeList. So you need to iterate through it to get value of individual elements. But you should not use for..in. You can use forEach instead.
function submitCodes() {
var QRCodeval = document.querySelectorAll("#scanned-result>div");
var arr = [];
QRCodeval.forEach((el) => arr.push(el.innerHTML));
console.log(arr)
}
submitCodes();
<div class="container">
<div class="row">
<div class="col-md-12" style="text-align: center;margin-bottom: 20px;">
<div id="reader" style="display: inline-block;"></div>
<div class="empty"></div>
<div id="scanned-result">
<div>[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp</div>
<div>[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0</div>
</div>
</div>
</div>
</div>
To get the text inside of the elements you can use innerHTML.
Since there is no <scanned-result></scanned-result> element on your page, as charlietfl pointed out, you won't get any results.
Since your HTML markup is the following:
<div id="scanned-result">
<!-- … -->
</div>
You are looking for an ID.
And the valid ID query in a CSS selector is a #, because of that you should query like:
var QRCodeval = document.querySelectorAll('#scanned-result')
I've changed the iteration to fill the array with the lines inside the ID scanned-result. Would that help ?
function SubmitCodes() {
var QRCodeval = document.getElementById('scanned-result').children;
var arr = [];
for (var i = 0; i < QRCodeval.length; i++) {
arr.push(QRCodeval[i].innerText)
}
console.log(arr)
}
<div class="container">
<div class="row">
<div class="col-md-12" style="text-align: center;margin-bottom: 20px;">
<div id="reader" style="display: inline-block;"></div>
<div class="empty"></div>
<div id="scanned-result">
<div>[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp</div>
<div>[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0</div>
</div>
</div>
</div>
</div>

How get content of all element with same class name?

Get content of all elements with the same class name using javascript.
How can I get all innerHTML-content from elements with the same class? I tried the code described below but it doesn't work I only get the first "Hello" from element but I don't get "World! from the second element" Of course there will be many more elements with the same class, not just two.
function myFunction() {
var child = document.querySelectorAll(".child");
var child, i;
for (i = 0; i < child.length; i++) {
var childall = child[i].innerHTML;
}
document.getElementById("demo").innerHTML = childall;
}
<div class="parent" id="parent">
<div class="child" id="child">Hello</div>
<div class="child" id="child">World!</div>
</div>
<button onclick="myFunction()">click</button>
<div class="demo" id="demo">
Move childall out of the loop, and assign an array to it. Now push all innerHTML values into it. After the loop ends join the array to a string, and assign to demo.
function myFunction() {
var child = document.querySelectorAll(".child");
var child, i;
var childall = [];
for (i = 0; i < child.length; i++) {
childall.push(child[i].innerHTML);
}
document.getElementById("demo").innerHTML = childall.join('<br>');
}
<div class="parent" id="parent">
<div class="child" id="child">Hello</div>
<div class="child" id="child">World!</div>
</div>
<button onclick="myFunction()">click</button>
<div class="demo" id="demo">
Instead of a for loop, you can use Array.from() to get an array of children's innerHTML.
function myFunction() {
const childall = Array.from(document.querySelectorAll(".child"), el => el.innerHTML);
document.getElementById("demo").innerHTML = childall.join('<br>');
}
<div class="parent" id="parent">
<div class="child" id="child">Hello</div>
<div class="child" id="child">World!</div>
</div>
<button onclick="myFunction()">click</button>
<div class="demo" id="demo">

JS Value returning form all divs

I am trying to get first letter of firstname and lastname from a div and paste it in another div but it is pasting the same value in all divs and not taking unique value from each div.
Working Fiddle: https://jsfiddle.net/bv7w8dxg/1/
Issue Fiddle: https://jsfiddle.net/bv7w8dxg/
var takword = $('.nameholder').text().split(' ');
var text = '';
$.each(takword, function () {
text += this.substring(0, 1);
});
$('.avatarholder').text(text);
Markup
`
John Doe
<div class="main-holder">
<div class="nameholder">Kyle Davis</div>
<div class="avatarholder"></div>
</div>
<div class="main-holder">
<div class="nameholder">Seim Seiy</div>
<div class="avatarholder"></div>
</div>
<div class="main-holder">
<div class="nameholder">Momma Boy</div>
<div class="avatarholder"></div>
</div>`
You are using class selectors, which selects all elements with the given class name. That's why you have all the elements set with same value
You need to wrap your elements then process each row independently
I updated your code snippet to demonstrate this:
$('.row').each(function() {
var takword = $('.nameholder', this).text().split(' ');
var text = '';
$.each(takword, function () {
text += this.substring(0, 1);
});
$('.avatarholder', this).text(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="nameholder">John Doe</div>
<div class="avatarholder"></div>
</div>
<div class="row">
<div class="nameholder">Kyle Davis</div>
<div class="avatarholder"></div>
</div>
<div class="row">
<div class="nameholder">Seim Seiy</div>
<div class="avatarholder"></div>
</div>
<div class="row">
<div class="nameholder">Momma Boy</div>
<div class="avatarholder"></div>
</div>

get ALL id's of children elements

How do I get an array or something similar with ALL the id's of elements to a certain div?
Let's say I have someting like this:
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
I would then like an array that look's something like this
parent-div [
0: "div-no-1",
1: "div-no-2",
2: "div-no-3",
3: "div-no-3"
];
I've tried this...
$("#parent-div > div").attr("id");
...but it only gives me the first childs id, e.g. div-no-1. I want ALL of them
An alternative to Jack Bashford's solution using $.map:
const divIds = $.map($('#parent-div > div'), div => div.id);
console.log(divIds);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
Or, using .map and .get:
const divIds = $('#parent-div > div').map((i, div) => div.id).get();
console.log(divIds);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
Use jQuery's each and push the id to the array:
var parentDiv = [];
$("#parent-div > div").each((index, elem) => {
parentDiv.push(elem.id);
});
console.log(parentDiv);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
If you want to do it in pure JavaScript, you can just get the children of the parent element and then loop over the result and push the ids into an array.
var children = document.getElementById("parent-div").children;
var idArr = [];
for (var i = 0; i < children.length; i++) {
idArr.push(children[i].id);
}
console.log(idArr);
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
This can be done in plain JavaScript using document.querySelectorAll('#paren-div > div') followed by a map() and some destructuring to get the id.
const ids = [...document.querySelectorAll('#parent-div > div')].map(({ id }) => id);
console.log(ids);
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
Give map a try
var arr = jQuery.map($("#parent-div").children(), function (d) {
return $(d).attr("id");
});
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
You can use .querySelectorAll() with Descendant combinator
Descendant combinator The (space) combinator selects nodes that are
descendants of the first element. Syntax: A B
"#parent-id [id]" to match all child nodes having an id attribute, spread syntax to convert NodeList to Array and Array.prototype.map()
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div></div>
<div class="div-no-2-6-6"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
text
</div>
<script>
let ids = [...document.querySelectorAll("#parent-div [id]")].map(({id}) => id);
console.log(ids);
</script>
The without jquery solution :
const elements = [...document.querySelectorAll('#parent-div *[id]')];
console.log(elements.map(({ id }) => id));
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
You can try this:
// Make an empty arary to push ids into
var arrayOfIds = [];
// Select parent element
var parentElement = document.querySelector('#parent-div');
// Select child elements
var childElements = parentElement.querySelectorAll("div");
// Push the id attribute of every child element
// Into he previousely created array
for (var i = 0; i < childElements.length; i++) {
arrayOfIds.push(childElements[i].getAttribute("id"));
}
console.log(arrayOfIds);
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
You can use .getAttribute("class") to get the CSS classes of all the elements, or any other attribute, by the same logic.
var ids = [];
$("#parent-div > div").each(function( index ) {
ids.push($(this).attr('id'));
});

Convert rows of Div values into an array with jQuery

Example:
I have a variable amount of rows, each with 3 divs with classes like so:
<div class="row>
<div class='date'>1/2/2018</div>
<div class='event'>concert</div>
<div class='act'>Pink Floyd</div>
</div>
<div class="row>
<div class='date'>12/5/2017</div>
<div class='event'>dj set</div>
<div class='act'>Moby</div>
</div>
<div class="row>
<div class='date'>5/5/2018</div>
<div class='event'>movie</div>
<div class='act'>Ant-Man</div>
</div>
How can I use jQuery to gather them into an associative array that I'll be passing to php to INSERT into a database table?
You can use map to loop thru the .row div. Use reduce to group the inner divs into a js object.
var result = $('.row').map(function() {
return $(this).find('div').toArray().reduce(function(c, v) {
c[$(v).attr('class')] = $(v).text();
return c;
}, {});
}).get();
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class='date'>1/2/2018</div>
<div class='event'>concert</div>
<div class='act'>Pink Floyd</div>
</div>
<div class="row">
<div class='date'>12/5/2017</div>
<div class='event'>dj set</div>
<div class='act'>Moby</div>
</div>
<div class="row">
<div class='date'>5/5/2018</div>
<div class='event'>movie</div>
<div class='act'>Ant-Man</div>
</div>
To select each all the div with the class row use this
var rows=$('div.row');
To loop through it use this
var array=[];
for(var i=0;i <rows.length;i++){
$.each(rows,function(){
var children=this.children('div');
$.each(children,function(){
var index=this.attr('class');
var value=this.text();
array[i][index]=value;
});
});
}
console.log(array);

Categories

Resources