Create list from each - javascript

I am looping through elements using jQuery like this:
$(".myelement").each(function() {
$element = $(this).closest(".panel").attr("id");
console.log($element);
});
This is working correctly and I am seeing each of the elements it finds in my console log. I am now trying to get a string containing each element that looks like this:
#element1, #element2, #element3
What is the easiest way to do this? Does anybody have an example they can point me at?

You could use map() to build an array of the id then join() it, something like this:
var ids = $(".myelement").map(function() {
return '#' + $(this).closest(".panel").prop("id");
}).get().join(', ');
console.log(ids);

You could use an array to store them by adding the # in every iteration, then after the loop end join them using join() method like :
var ids = [];
$(".myelement").each(function() {
ids.push('#' + $(this).closest(".panel").attr("id"));
});
console.log(ids.join(', '));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element1" class="panel">
<span class="myelement">My element 1</span>
</div>
<div id="element2" class="panel">
<span class="myelement">My element 2</span>
</div>
<div id="element3" class="panel">
<span class="myelement">My element 3</span>
</div>

Try with map()
The .map() method is particularly useful for getting or setting the value of a collection of elements.
As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.
You can use map(), get() and join()
in the following way:
var $element = $(".myelement").map(function(){
return $(this).closest(".panel").attr("id");
}).get().join(', ');
console.log($element);

Related

Why does my document.getElementsByClassName("obj").innerHTML doesn't work?

I want to replace HTML in document with .innerHTML but for some reason it doesn't work:
HTML
<div class="specs">
<div class="wrapp">
<p class="line">Content</p>
</div>
</div>
JS
document.getElementsByClassName("specs").innerHTML = "<p>Lorem ipsum</p>";
getElementsByClassName returns a collection. Not a single item.
There are multiple ways to do this:
You can run a for loop over the returned items.
let specs = document.getElementsByClassName("specs");
for(let i = 0 ; i < specs.length;i++){
specs[i].innerHTML = "<p>Lorem ipsum</p>";
}
If you have only item, you can use querySelector which returns the first matched element.
document.querySelector(".specs").innerHTML = "<p>Lorem ipsum</p>";
In a concise way this is how you'd do it
const targets = document.getElementsByClassName("specs")
if (targets.length)
for (spec in targets)
targets[spec].innerHTML = "<p>Lorem ipsum</p>";
<div class="specs">
<div class="wrapp">
<p class="line">Content</p>
</div>
</div>
I found your mistake.
document.getElementsByClassName returns an array of elements with the given class name. so try this.
document.getElementsByClassName("specs")[0].innerHTML = "<p>Lorem ipsum</p>";
For example if you have two elements with the same class name it returns an array containing both the elements, so you have to get the element using the specified index from the array. 👍

Sort jQuery Result By Attribute?

Is it possible to sort a jQuery result by an attribute's value? For example, consider the following code snippet and result:
$('span').each(function()
{
$('#log').append($(this).attr('name'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<span name="a5"></span>
<span name="a3"></span>
<span name="a6"></span>
<span name="a1"></span>
<span name="a4"></span>
<div id="log"></div>
Without modifying the HTML or DOM, how can I best modify this code to get a sorted result, ie. a1a3a4a5a6? Though I could obviously stick each result in an array and then sort it afterwards, I'm assuming there's a more elegant way using jQuery's native abilities. Is there?
You don't need to build intermediate array, jQuery exposes Array.prototype.sort method for convenience:
$.fn.sort = Array.prototype.sort;
and since Array.prototype.sort; is generic (*) it just magically works with jQuery collections too.
$('span')
.sort(function(a, b) {
return $(a).attr('name').localeCompare($(b).attr('name'));
})
.each(function() {
$('#log').append($(this).attr('name'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span name="a5"></span>
<span name="a3"></span>
<span name="a6"></span>
<span name="a1"></span>
<span name="a4"></span>
<div id="log"></div>
* Generic in context of prototype methods means that methods internal implementation does not care about this instance being a real Array instance, as soon as it's an array-like collection.
Try with this code:
var $names = $('span');
var $log = $('#log');
$names.sort(function(a,b){
var aProp = a.getAttribute('name'),
bProp = b.getAttribute('name');
if (aProp > bProp){
return 1;
}
if (aProp < bProp){
return -1;
}
return 0;
});
$names.appendTo($log);

JSON array from tag names attr and values

Let's suppose, I have this code:
<div>
<div>
<span class="toarray" name="someName-1">someDynamicValue</span>
</div>
<div>
<span class="toarray" name="someName-2">someDynamicValue</span>
</div>
<div>
<span class="toarray" name="someName-3">someDynamicValue</span>
</div>
</div>
I want to create JSON array from this code:
{
someName-1: "someDynamicValue",
someName-2: "someDynamicValue",
someName-3: "someDynamicValue"
}
You can try something like bellow
var data = {};
$('span.toarray').each(function(){
data[$(this).attr('name')] = $(this).text();
});
console.log(data);
Demo
Do this.
Get all the spans with class toarray, loop over them, get each spans text along with attr('name') and push into an object defined above the loop.

Get concatenated text of elements using JavaScript

I tried it with getElementById and it worked. But now I want the same with multiple div's so I have to use classes. So I changed the method to getElementsByClassName and now it says undefined.
(The function is called when a option in a select changes. This works correctly)
HTML:
<div class="item_content">
<h3 class="filmnaam">22 jump street</h3>
</div>
<div class="item_content">
<h3 class="filmnaam">rio 2</h3>
</div>
Javascript:
function sorting(sortingway) {
alert(sortingway.value);
var titelfilms = document.getElementsByClassName("filmnaam");
var titels = titelfilms.innerHTML;
console.log(titels[0]);
}
Is there a way to do this without jQuery?
getElementsByClassName returns a collection, so loop that!
var titelfilms = document.getElementsByClassName("filmnaam");
for (var i = 0; i < titelfilms.length; i++) {
var titels = titelfilms[i].innerHTML;
console.log(titels);
}
titelfilms is a node list, you can't get the innerHTML of a node list as a whole, it contains multiple references to elements which each have their own individual property.
You could loop through and concatenate each innerHTML onto a variable, or you could map() the innerHTML of your returned elements to an array and then join() them up:
function sorting(sortingway) {
var titelfilms = document.getElementsByClassName("filmnaam");
var titels = Array.prototype.map.call(titelfilms, function (el) {
return el.innerHTML;
}).join(' ');
console.log(titels);
}
sorting();
<div class="item_content">
<h3 class="filmnaam">22 jump street</h3>
</div>
<div class="item_content">
<h3 class="filmnaam">rio 2</h3>
</div>

iterate over all classes within a given class

<div class="contain_questions">
<div class="question">
<div class="question_text">First question</div>
<div class="question_mandatory">1</div>
<div class="options">
<div class="option"><div class="option_name">a</div><div class="option_value">1</div></div>
<div class="option"><div class="option_name">b</div><div class="option_value">2</div></div>
<div class="option"><div class="option_name">c</div><div class="option_value">3</div></div>
</div>
add_another_option
</div>
.
. // many more div.question ...
.
<input type="button" value="submit_questions" />
</div>
How do you use .each() for each div.option within an outer .each() for each question?
I have the outer .each() working fine, which iterates over all div.question and pushes the question_text etc into an array, however I cant seem to target the options container within each question in order to also push all of the options for each question into the array.
Also, is it possible to target a subset of the DOM with the .each() function, or is there some other way to iterate over all classes within a given class?
Thanks guys..
Just as simple as that:
$(".question").each(function() {
...
$(this).find(".option").each(function() {
...
});
});
So your code might look like the following:
var questions = [];
$(".question").each(function() {
var obj = {
name : $(this).find(".question_text").text(),
options : []
};
$(this).find(".option").each(function() {
obj.options.push({
name : $(this).find(".option_name").text(),
value : $(this).find(".option_value").text()
});
});
questions.push(obj);
});
console.log(questions);

Categories

Resources