i have following code and want to get the id of all elements that belong to particular class.
code
<ul>
<li><label class="check-lbl"><input id="1" class="translation_box" type="checkbox">اردو</label</li>
<li><label class="check-lbl"><input id="3" class="translation_box" type="checkbox">Englisg</label> </li>
<li><label class="check-lbl"><input id="4" class="translation_box" type="checkbox">Hindi</label> </li>
<li><label class="check-lbl"><input id="5" class="translation_box" type ="checkbox">Bungali</label> </li>
< /ul>
here i am talking translation_box. any help will be appreciated!
You can use .map() to directly get the list of IDs from a jquery collection.
var ids = $('.translation_box').map(function(_, x) { return x.id; }).get();
Demo: http://jsfiddle.net/ZNxP7/1/
Using jQuery
$('.translation_box').each( function () {
alert($(this).prop('id'));
});
Using JS
var ele = document.getElementsByClassName('translation_box');
for (var i=0; i< ele.length; i++ ) {
alert(ele[i].id);
}
JSFiddle
var allItemsInClass = $(".translation_box");
var arrayIDs = new Array();
$.each(allItemsInClass, function() {
arrayIDs.push(this.id);
});
alert(arrayIDs.join());
DEMO: http://jsfiddle.net/LG59D/
You can use jQuery to do so.
$(function(){
var elements = new Array();
$('.translation_box').each(function(){
elements.push($(this).attr("id"))
});
})
$('.translation_box').each(function() { // this loops through all elements with class of tranlation_box
var x = $(this).attr('id'); // this gets the id of each translation_box and stores it in the variable x
console.log(x); // this logs the id for each one
});
You can do it like the following:
function getIds() {
var elements = document.getElementsByClassName("translation_box");
for(var i=0; i<elements.length; i++) {
console.log(elements[i].getAttribute("id"));
}
}
It returns all id's in an Array
var idArray = [];
$('.translation_box').each(function() {
var id = $(this).attr('id');
idArray.push(id);
});
alert(idArray)
Related
im having a bit of trouble with the code below:
Html:
<p>click to <a onclick ="sortList(); return false;" href="#">sort</a></p>
<ul id="fruits">
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>
Javascript:
function sortList(listId) {
var list = document.getElementbyId(listId);
var children = list.childNodes;
var listItemsHTML = new Array();
for (var i = 0; i < children.length; i++) {
if (children[i].nodeName === "LI") {
listItemsHTML.push(children[i].innerHTML);
}
}
listItemsHTML.sort();
list.innerHTML="";
for (var i = 0; i < listItemsHTML.length; i++) {
list.innerHTML += "<li>" + listItemsHTML[i] + "</li>";
}
}
however, when i try and click the link to sort the html does nothing and im not sure what the problem is. i am referencing and was able to use changeit and echo function to produce an alert message in the .js file just cant sort
You need to pass the listId to the function as an argument like onclick ="sortList('fruits'); return false;" and change document.getElementbyId() to document.getElementById() which is a typo
function sortList(listId) {
var list = document.getElementById(listId);
var children = list.childNodes;
var listItemsHTML = new Array();
for (var i = 0; i < children.length; i++) {
if (children[i].nodeName === "LI") {
listItemsHTML.push(children[i].innerHTML);
}
}
console.log(listItemsHTML);
listItemsHTML.sort();
list.innerHTML="";
for (var i = 0; i < listItemsHTML.length; i++) {
list.innerHTML += "<li>" + listItemsHTML[i] + "</li>";
}
}
<p>click to <a onclick ="sortList('fruits'); return false;" href="#">sort</a></p>
<ul id="fruits">
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>
Firstly, it's document.getElementById ... capital B in ById
Secondly, use list.children rather than list.childNodes - don't need to care about text nodes
Thirdly, use list.appendChild on a sorted list to move the existing nodes, rather than mucking around with innerHTML
function sortList(listId) {
var list = document.getElementById(listId);
Array.from(list.children).sort((a, b) => a.textContent > b.textContent).forEach(li => list.appendChild(li));
}
Or, if you're not comfortable with ES2015+
function sortList(listId) {
var list = document.getElementById(listId);
Array.from(list.children).sort(function (a, b) {
return a.textContent > b.textContent;
}).forEach(function (li) {
return list.appendChild(li);
});
}
and finally, change
<a onclick ="sortList(); return false;" href="#">
to
<a onclick ="sortList('fruits'); return false;" href="#">
I know its already answered, but of thought of providing little different version.
Use buttons instead of <a>, Using 'href='#' is not a good practice.
Never create a element from string. Always use document.createElement. Its better!
Write a separate listener for triggering functions. Don't write in HTML itself. It will be harder to manage once application grows.
HTML
<p>click to <button class="sort">sort</button></p>
<ul id="fruits">
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>
JavaScript
<script type="text/javascript">
function sortList() {
var fruitCollection = [],
fruitsDOM = document.querySelector('#fruits'),
fruitsLists = document.querySelectorAll('li');
fruitsLists.forEach(function(item) {
fruitCollection.push(item.textContent);
});
fruitCollection.sort();
fruitsDOM.innerHTML = null;
fruitCollection.forEach(function(item) {
var newNode = document.createElement('li');
newNode.textContent = item;
fruitsDOM.appendChild(newNode);
});
}
document.querySelector('.sort').addEventListener('click', sortList);
</script>
I have a list like this:
<ul class="draggable">
<li data-bullet="1"> item 1</li>
<li data-bullet="2"> item 2</li>
<li data-bullet="3"> item 3</li>
</ul>
Using javascript, how do I grab all the list item attributes data-bullet and insert them into the value of an input (separated by a comma):
<input id="insertme" type="hidden" name="bullet" value="">
So the end result will be:
<input id="insertme" type="hidden" name="bullet" value="1,2,3">
I know how to get individual list items but can't get my head around how to get them all and insert them there.
Here you go, A pure javascript solution
Try to use dataset at this context,
var res = "";
[].forEach.bind(document.querySelectorAll(
'.draggable > li[data-bullet]'),function(itm, i){
res += ((i) ? ":" : "") + itm.dataset.bullet;
})();
document.getElementById("insertme").value = res;
DEMO
Or the less complex and a readable version would be,
var elemArray = Array.from(document.querySelectorAll('.draggable > li[data-bullet]')),
res ="";
elemArray.forEach(function(){
res += ((i) ? ":" : "") + itm.dataset.bullet;
});
document.getElementById("insertme").value = res;
As per your new requirement, you can accomplish your task by,
$("button").click(function() {
var parent = $(this).parent();
parent.closest(".draggable").next(":text").val(parent.siblings("li").addBack().map(function(){
return $(this).data("bullet")
}).get().join(":"));
});
DEMO
try
var allBullets = [];
$(".draggable li").each(function(){
allBullets.push($(this).attr("data-bullet"));
});
$("#insertme").val(allBullets.join(","));
If you can use querySelectorAll to find elements and then map it using getAttribute method. For example (ES6 syntax):
const items = document.querySelectorAll('.draggable li');
const result = [...items].map(el => el.getAttribute('data-bullet')).join();
document.getElementById('insertme').value = result;
ES5 analogy:
var items = document.querySelectorAll('.draggable li');
var result = [].slice.call(items).map(function(el) {
return el.getAttribute('data-bullet');
}).join();
document.getElementById('insertme').value = result;
i am trying to build post it notes. I am reading Head First Series.
I did this code.
but somehow it's no working.
<form action="post">
<input id="note_text" type="text" placeholder="enter your Note">
<input type="button" id="add_button" value="Add Note">
</form>
<ul id="postItNotesList">
<li>This is my very first note.</li>
<li>This is my very Second note.</li>
</ul>
And here is the Js
window.onload=init;
// Add Sticky to Page
function addStickyToPage(value) {
var sticky = document.createElement("li");
span.setAttribute("class", "sticky");
document.getElementById("postItNotesList").appendChild(sticky);
}
// Create and get Sticky Note into the localStorage
function createSticky() {
var value = document.getElementById("note_text").value;
var key = "sticky_" + localStorage.length;
localStorage.setItem(key, value);
addStickyToPage(value);
}
function init() {
var button = document.getElementById("add_button");
button.onclick = createSticky;
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
if (key.substring(0, 6) == "sticky") {
var value = localStorage.getItem(key);
addStickyToPage(value);
}
}
}
So i've buld up a fiddle so that you can easily check it out
Here is the Fiddle
Please tell me where i am doing it wrong.
Thanks.
I have updated your Fiddle. Note : first you should create DOM element and then append text to this element and finally append this node to you body so your code should be like this:
window.onload=init();
function addStickyToPage(value) {
var sticky = document.createElement("li");
sticky.setAttribute("class", "sticky");
var t = document.createTextNode(value);
console.log(t);
sticky.appendChild(t);
document.getElementById("postItNotesList").appendChild(sticky);
}
And also windows.onload = init()with brackets
Thanks
Here I am going to make a tag cloud manually.Everything is going well but I face a little problem. Below is my code :
HTML:
<ul id="tagCloud">
<li id="tagcloud_li">Item1</li>
<li id="tagcloud_li">Item2</li>
</ul>
<div id="vis">
<div class="set_texts">
</div>
</div>
JavaScript :
$(function() {
var liArray = document.getElementsByTagName('li');
var list_item = [];
for(var i=0; i < liArray.length ;i++){
list_item.push($(liArray[i]).text());
var get_item_value = ($(liArray[i]).text());
var create_text = $('#vis').find('.set_texts').append($('<a href="" id="tagcloud_list" class="tagcloud_li'+i+'">'));
$('#vis').find(".tagcloud_li"+i).text($(liArray[i]).text());
}
var count_li = $('#vis').find('#tagcloud_list').length+1;
for(var i=0; i < liArray.length ;i++){
for(var j = 0; j < count_li; j++){
if(i == j){
var get_item_value = ($(liArray[i]).text());
var get_class = $('#vis').find('a').text(get_item_value).append(get_class);
}
}
}
});
Output of this code is :
Item2
Item2
In this output both contain value 'Item2'.
But I want to get value 'item1' in first tag 'a' and value 'item2' in second tag 'a' .Like :
Item1
Item2
How I can get this?
HTML:
<ul id="tagCloud">
<li id="tagcloud_li">Item1</li>
<li id="tagcloud_li">Item2</li>
</ul>
<div id="vis">
<div class="set_texts"></div>
</div>
CSS:
.set_text {
height:500px;
width:500px;
background-color:#FFFFFF;
font-family:Arial;
border: 1px solid #FFFFFF;
text-align:left;
}
.tagcloud {
font-size:12px;
text-decoration:none;
color: #FF7600;
}
JS:
$(function () {
var container = $("#vis").find(".set_texts");
$("#tagCloud").find('li').each(function (i) {
$('<a href="" id="tagcloud_list" class="tagcloud tagcloud_li' + i + '"/>').text($(this).text()).appendTo(container);
});
});
Sample: (Fiddle)
Created tag cloud is simple but it's what your code does.
Your code is very complex and thus you won't see the point for sure. I.e.,
var liArray = document.getElementsByTagName('li');
var list_item = [];
for(var i=0; i < liArray.length ;i++){
list_item.push($(liArray[i]).text());
var get_item_value = ($(liArray[i]).text());
var create_text = $('#vis').find('.set_texts').append($('<a href="" id="tagcloud_list" class="tagcloud_li'+i+'" style="font-size:12px;text-decoration:none; color: #FF7600;">'));
$('#vis').find(".tagcloud_li"+i).text($(liArray[i]).text());
}
might be reduced to this:
$("li").each(function() {
var item = $(this);
var text = item.text();
$('<a href="" class="tagcloud_list" id="tagcloud_li'+i+'" style="font-size:12px;text-decoration:none; color: #FF7600;">')
.text( text )
.appendTo( $('#vis').find('.set_texts') );
});
Your example of this loop is fetching same information from DOM several times and drops it in one of those cases. That's expensive by means of performance. Next you might reverse way of adding the <a> so you won't need to add it to the target container first just to get query that one to give it back afterwards.
The resulting <a> are all using same ID which is bad, too. So try swapping class and ID.
According to your issue this code seems to be crucial:
var get_class = $('#vis').find('a').text(get_item_value).append(get_class);
It is finding all <a> in your target assigning single text to all of them.
Change your Javascript to this.. And I used Jquery..
$(document).ready(function(){
var liArray = $("li");
var i;
for(i=0;i < liArray.length;i++){
$("div.set_texts").append('' + liArray[i].innerHTML + '');
}
});
I have a list of checkbox as below :
The code for that list is :
#foreach (extranetClient.Models.Classes.FonctionContact fonction in ViewBag.Fonctions)
{
string coche = "";
if ((#Model.ListeFonctions).Any(c => c.IdFonction == fonction.IdFonction))
{
coche = "checked";
}
<input type="checkbox" #coche id="checkbox" value="#fonction.IdFonction" />#fonction.LibelleFonction <br />
}
So now I would like to get the values of all the ckeckboxes which are checked in the list everytime I check one of them. So I've tried that :
$("#checkbox").click(function () {
var TabIdFonctions = new Array();
var compteur = 1;
$("input[type='checkbox']:checked").each(
function () {
TabIdFonctions[compteur] = $(this).val();
compteur++;
});
});
But it doesn't work and I don't really know why. Hope somebody has an idea.
In javascript arrays are 0 indexed. But you could use the .push method instead. Also you should use a class selector, not an id selector because you can have only one element with a given id:
$('.checkbox').click(function () {
var TabIdFonctions = new Array();
$('.checkbox:checked').each(function () {
TabIdFonctions.push($(this).val());
});
});
Also don't forget to give your checkboxes a class, not id:
<input type="checkbox" #coche class="checkbox" value="#fonction.IdFonction" />
javascript code
var els = document.getElementsByTagName('input');
for (var i = 0; i < els.length; i++) {
var el = els[i];
if (el.checked == true) {
TabIdFonctions.push(el.value);
}
}