Get id's of all child elements with a particular class - javascript

I need to get the id's of the 'vehicle' class from the <ul>. How can I get that using jquery/javascript? Can it be done with iterating through all the elements? Thanks in advance.
<ul id="ulList">
<li id="car" class="vehicle">
<li id="bus" class="vehicle">
<li id="cat" class="animal">
<li id="dog" class="animal">
<li id="bike" class="vehicle">
<li id="monkey" class="animal">
</ul>

Use map().
Also, correct your HTML markup like in the snippet(class="").
Finally, use .get() if you need a true JavaScript array (instead of a jQuery collection of strings — jQuery's collections [sets] usually contain DOM elements, but can contain anything).
var ids = $('#ulList .vehicle').map(function(){
return $(this).attr('id');
}).get();
console.log(ids);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<ul id="ulList">
<li id="car" class="vehicle"></li>
<li id="bus" class="vehicle"></li>
<li id="cat" class="animal"></li>
<li id="dog" class="animal"></li>
<li id="bike" class="vehicle"></li>
<li id="monkey" class="animal"></li>
</ul>

As there are already other answers with jQuery, here is an alternative using vanila Javascript:
var vehicles = document.querySelectorAll("ul#ulList > li.vehicle");
var ids = [].map.call(vehicles, function(elem) {
return elem.id;
});
console.log(ids);
<ul id="ulList">
<li id="car" class="vehicle">
<li id="bus" class="vehicle">
<li id="cat" class="animal">
<li id="dog" class="animal">
<li id="bike" class="vehicle">
<li id="monkey" class="animal">
</ul>

vehicleIds is an array to which you push all the ids of elements whose class is vehicle.
var vehicleIds = [];
$(".vehicle").each(function(){
vehicleIds.push($(this).attr("id"));
});
alert(vehicleIds);
Then I alert the array at the end.

$('div','#main').each(function(){
array.push($(this).attr('id'));
});
Here div is the element whose children's id have to be pushed in an array & '#main' is the id of that div.
Hope this will help you.

Related

Selecting list items by id without jquery

I have a list in html of this type
<ul>
<li id="1.1" fatherid="1"> ...</li>
<li id="1.2" fatherid="1"> ...</li>
<li id="1.3" fatherid="1"> ...</li>
...
</ul>
And I want to select all the items of the list with a given fatherid. For example I'd like to select all the items with "1" as fatherid, but I don't know how to do it. I tried with querySelectorAll and getElementById but it didn't work, and I prefer not to use jquery.
Thanks for the answers.
You can use data-attributes (https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes) to store the fatherids (which is the recommended way to add custom attributes to html elements). You can then find the tags with a given fatherid using the [data-fatherid] selector.
function getByFather(id) {
return document.querySelectorAll(`[data-fatherid='${id}']`);
}
console.log([...getByFather(1)]);
console.log([...getByFather(2)]);
<ul>
<li id="1.1" data-fatherid="1">1.1</li>
<li id="1.2" data-fatherid="1">1.2</li>
<li id="1.3" data-fatherid="1">1.3</li>
<li id="2.1" data-fatherid="2">2.1</li>
<li id="2.2" data-fatherid="2">2.2</li>
</ul>
Since Document.querySelectorAll accepts a selector we can make use of the CSS attribute selector:
const r = document.querySelectorAll('li[fatherid="1"]');
console.log(Array.from(r));
<ul>
<li id="1.1" fatherid="1"> ...</li>
<li id="1.2" fatherid="1"> ...</li>
<li id="1.3" fatherid="1"> ...</li>
</ul>

I cannot get access to all desired elements using querySelectorAll

So I have these three lists which I want to hide.
<ul id="wordsb" class="wordslist" class="list1">
<li class="list-group-item">list1</li>
<li class="list-group-item">dancing</li>
<li class="list-group-item">elephant</li>
</ul>
<ul id="wordsb1" class="wordslist" class="list2">
<li class="list-group-item">list2</li>
<li class="list-group-item">man</li>
<li class="list-group-item">dog</li>
</ul>
<ul id="wordsb2" class="wordslist" class="list3">
<li class="list-group-item">list3</li>
<li class="list-group-item">plane</li>
<li class="list-group-item">truck</li>
</ul>
I am using the queryselectorall in order to access the ids loop through them, applying a style to each of them:
var gameb = document.querySelectorAll("#wordsb", "#wordsb1", "#wordsb2");
for (var i = 0; i < gameb.length; i++) {
gameb[i].style.display = "none";
}
Unfortunately, only the first list (wordsb) is hidden as desired, and the remaining two elements do not seem to be impacted. When I console.log(gameb) I found that the node list only includes wordsb, and not the other two elements. enter code here
querySelectorAll only takes one parameter:
var gameb = document.querySelectorAll("#wordsb, #wordsb1, #wordsb2");
for (var i = 0; i < gameb.length; i++) {
gameb[i].style.display = "none";
}
<ul id="wordsb" class="wordslist" class="list1">
<li class="list-group-item">list1</li>
<li class="list-group-item">dancing</li>
<li class="list-group-item">elephant</li>
</ul>
<ul id="wordsb1" class="wordslist" class="list2">
<li class="list-group-item">list2</li>
<li class="list-group-item">man</li>
<li class="list-group-item">dog</li>
</ul>
<ul id="wordsb2" class="wordslist" class="list3">
<li class="list-group-item">list3</li>
<li class="list-group-item">plane</li>
<li class="list-group-item">truck</li>
</ul>
This was just a silly mistake, document.queryselectorall only takes one parameter, and I accidentally put quotation marks around each of my elements. Thereby, making multiple parameters. Thus the node list didnt reflect all three of my elements.

Move li element with javascript

I would like to move a li element after a list of li with the same class, is that possible?
$("li#anonymous_element_2").insertAfter("li.amscheckout-row:last");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="amscheckout-row"> </li>
<li class="amscheckout-row"> </li>
<li class="amscheckout-row"> </li>
<li class="fields" id="anonymous_element_2"> </li>
<li class="amscheckout-row"> </li>
<li class="amscheckout-row"> </li>
<li class="amscheckout-row"> </li>
<li class="amscheckout-row"> </li>
jQuery has a built in last() function:
var elementToMove = $('#anonymous_element_2');
var targetPosition = $('.amscheckout-row').last();
elementToMove.insertAfter(targetPosition);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="amscheckout-row">1</li>
<li class="amscheckout-row">2</li>
<li class="amscheckout-row">3</li>
<li class="fields" id="anonymous_element_2">4</li>
<li class="amscheckout-row">5</li>
<li class="amscheckout-row">6</li>
<li class="amscheckout-row">7</li>
<li class="amscheckout-row">8</li>
Yes you can!
The method that should fit your requirements is: after.
If I understand you want to "move" and, to do that, you have to "remove/add" the element into the list of values.
I suggest you to try this code:
var $liToAppend = $('li#anonymous_element_2');
var $lastLi = $('ul li:last'); // I suppose you are using the root tag UL!
// The final solution:
$liToAppend.remove();
$lastLi.after($liToAppend);
With jQuery you can to this in lot of ways:
$('li#anonymous_element_2').remove().appendTo('ul');
Should work too!
Try This
<script>
$("<li>Hello world!</li>").insertAfter(".amscheckout-row:last")
</script>

Is it possible to iterate over a Bootstrap list?

I have a Twitter Bootstrap list with a variable number of elements (in fact there are two lists with draggable and droppable elements done with Sortable.js).
At some point, I want to iterate those lists elements in order to get a data atribute from each list entry. This is how my list looks like at HTML:
<div class="panel-body">
<ul id="main_list" class="list-group">
<li id="opt1" href="#" class="list-group-item" data_value="1">Opt 1</li>
<li id="opt2" href="#" class="list-group-item" data_value="2">Opt 2</li>
<li id="opt3" href="#" class="list-group-item" data_value="3">Opt 3</li>
</ul>
</div>
Is this even possible to achieve, or am I thinking too object oriented? If not, how should I rethink this task?
You can put your specific information like
<li id="opt3" href="#" class="list-group-item" data-value="3">Opt 3</li>
and get that easily with jquery:
$("#opt3").data("value")
But the semantic way to do that is with "-" instead of "_".
To iterate your list, you can do:
$("#main_list li").each(function(){
var itemValue = $(this).data('id');
var itemName = $(this).data('name');
alert(itemValue+" - " +itemName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-body">
<ul id="main_list" class="list-group">
<li id="opt1" href="#" class="list-group-item" data-name="customname1" data-id="1">Opt 1</li>
<li id="opt2" href="#" class="list-group-item" data-name="customname2" data-id="2">Opt 2</li>
</ul>
</div>
Thiago's answer is totally valid, and if jQuery is already used then it should be the accepted answer. But for the sake of it here is a solution in plain js:
var elements = document.getElementById('main_list').children,
maxElements = elements.length,
counter = 0,
tmpAttribute;
for (; counter < maxElements; counter++) {
tmpAttribute = elements[counter].getAttribute('data_value');
// whatever you need to do with tmpAttribute
}
You could wrap that in a function and call it on click for example. Here is a demo to see it in action: http://jsfiddle.net/Lzcbzq7x/1/

How can i access children using parent id

I have this structure of html. To present the list of two different sets. and i must handle the click event differently.
<div id='nodelist1'>
<ul>
<li class='nodeelem'>first node
<ul>
<li class='nodeelem'>second node
<ul>
<li class='nodeelem'>third node</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div id='nodelist2'>
<ul>
<li class='nodeelem'>first node
<ul>
<li class='nodeelem'>second node
<ul>
<li class='nodeelem'>third node</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
I have to access the nodes using div id
$('#nodelist1 li.nodeelem').click(handler);
$('#nodelist2 li.nodeelem').click(handler2);
Is this rightway to access children clicks???
You forgot the hash # for ID selectors (although you corrected this in your edit):
$('#nodelist1 li.nodeelem').click(handler);
$('#nodelist2 li.nodeelem').click(handler2);
Tip: you can make the event more effective by using on() instead for event delegation:
$('#nodelist1').on('click', '.nodeelem', handler);
$('#nodelist2').on('click', '.nodeelem', handler2);

Categories