I have the following structure:
<ul id="myTags"">
<li>
<span class="tagit-label">AA</span>
<a>
<span class="text-icon">×</span>
<span class="ui-icon ui-icon-close"></span>
</a>
<input type="hidden" name="tags" value="AA" style="display:none;">
</li>
<li>
<span class="tagit-label">BB</span>
<a class="tagit-close">
<span class="text-icon">×</span>
<span class="ui-icon ui-icon-close"></span>
</a>
<input type="hidden" name="tags" value="BB" style="display:none;">
</li>
....
</ul>
I want to write a Javascript/jQuery function that will create a string consists of
"AA,BB,..."
How do I collect the values from all of the value attribute at span rows?
This should work:
$('#myTags input[name="tags"]').map(function () {
return $(this).val();
}).get().join(",");
Try this
var textArr = [];
$(".tagit-label").each(function(){
textArr.push($(this).text());
})
console.log(textArr.join());
Use .map()
var array = $('.tagit-label').map(function(){
return $(this).text()
}).get()
console.log(array.join(','))
Demo: Fiddle
You can do this:
var arr = $('#myTags .tagit-label').map(function () {
return $(this).text();
}).get().join(",");
console.log(arr);
Here is my late answer. I tried javascript 1.8 array reduce method, for fun .
var string = [].reduce.apply( $('.tagit-label') , [ function( ar , n ){
return ar.push( $(n).text() ) && ar ;
},[] ] ).join();
or simply
var string = [].reduce.call( $('.tagit-label') , function( ar , n ){
return ar.push( n.innerHTML ) && ar ;
},[] ).join();
Hope this will help learning more on reduce method . http://jsfiddle.net/6TnMT/
var spans = $(".tagit-label");
var str = "";
for (i = 0; i < spans.length; i++) {
str += spans[i].innerHTML+"," ;
}
alert(str);
Fiddle Example
var str= $('.tagit-label').first().text();
$('.tagit-label:not(":first")').each(function(){
str= str +' , '+ $(this).text();
});
alert(str);
Related
I hate manually typing steps numbers. So I was trying to write a small function to find some text and replace it with generated step numbers.
And I can't use the ol/li tags because I have multiple groups on the page. So I need to add an "a", "b", etc after the number.
My HTML:
<span class="grouping" v="a">
----My first step
----This is another
----And another
</span>
<br/>
<span class="grouping" v="b">
----second group
----second group 2
</span>
This is my jquery (but it doesn't replace the ---- to a step number).
$(function(){
$(".grouping").each(function(){
var val=$(this).attr("v");
var counter=1;
$(this).find(":contains('----')").each(function(){
$(this).text("("+counter+val+") ");
counter++;
});
});
});
So eventually, I want the webpage to finish like this:
(1a) My first step
(2a) This is another
(3a) And another
(1b) second group
(2b) second group 2
For each of the groupings, get the inner html and split it by newline
If it starts with '----', replace it with an incrementing line number, and append the v value.
Put the html back into the grouping.
$('.grouping').each(function(index, grouping){
var lines = grouping.innerHTML.trim().split("\n");
var lineNumber = 0;
var v = grouping.getAttribute('v');
lines.forEach(function(line, index){
if (line.startsWith('----')) {
lines[index] = '('+ (++lineNumber) + v +') '+ line.slice(4);
}
});
grouping.innerHTML = lines.join('\n');
});
.grouping { white-space: pre; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="grouping" v="a">
----My first step
----This is another
I should not have a line number.
----And another
</span>
<br/>
<span class="grouping" v="b">
I also should not have a line number.
----second group
----second group 2
</span>
You can use split to split the text at '----' and concat with the values (added brs for lisibility so I used html instead of text):
$(function(){
$(".grouping").each(function(){
var val=$(this).attr("v");
var arr = $(this).html().split('----');
if(arr.length > 1){
var str = arr[0], i, l = arr.length;
for(i = 1; i < l; i++){
str += '(' + i + val + ') ' + arr[i];
}
$(this).html(str);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="grouping" v="a">
----My first step<br>
----This is another<br>
----And another<br>
</span>
<br/>
<span class="grouping" v="b">
----second group<br>
----second group 2<br>
</span>
.find() will not work. You should get text of the element and split() it and then change it using map() and replace() and reset text()
$(function(){
$(".grouping").each(function(){
var val=$(this).attr("v");
var counter=1;
let lines = $(this).text().split('\n');
lines = lines.map(ln => {
if(ln.includes('----')){
ln = ln.replace('----',`(${counter}${val})`)
counter++;
}
return ln;
})
lines = lines.filter(ln => ln !== '');
$(this).text(lines.join('\n'));
});
});
.grouping { white-space: pre; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="grouping" v="a">
----My first step
----This is another
----And another
</span>
<br/>
<span class="grouping" v="b">
----second group
----second group 2
</span>
First, I suggest wraping those groups into some kind of tag. for example, span:
<span class="grouping" v="a">
<span class="grouping-item">My first step</span>
</span>
And so on, it will be easier and faster to target those elements.
Then create one function to search through those new tags
$(function(){
// This will create those numbers
function createNumbers(el) {
const mainGroup = el.attr("v");
const children = el.children(".grouping-item");
let i = 1;
children.each(function(){
const currentText = $(this).text();
$(this).text( '('+i+mainGroup+')' + currentText );
i++;
});
}
$(".grouping").each(function(){
createNumbers($(this));
});
});
I am getting a variable which value always follows this format:
"<div>
</div>
<div>
<span style="font-family:tahoma,geneva,sans-serif;"><span>VALUE 1</span></span></div>
<div>
<strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div>
<div>
<span style="font-family:tahoma,geneva,sans-serif;"> </span>VALUE 3</div>
"
How can I get VALUE 1, VALUE 2 and VALUE 3 using JavaScript (not jQuery or other libs)?
NB:
in Console, I get those values (I call them b)
typeof(b) returns string
The most simplest way using jQuery.
var a = '<div>\
</div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;"><span>VALUE 1</span></span></div>\
<div>\
<strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;">au </span>VALUE 3</div>'
var HTML = $.parseHTML(a)
var val1 = $(HTML[1]).find('span span').text()
var val2 = $(HTML[2]).find('span').text()
$(HTML[3]).find('span').remove()
var val3 = $(HTML[3]).text()
console.log(val1, val2, val3)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Use Array#map and then Array#filter
innerHTML the string to a temp element and use DOM-api to manipulate data.
Use 'span[style]' selector to get only those span elements having style attribute.
var str = '<div>\
</div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;"><span>VALUE 1</span></span>\
</div>\
<div>\
<strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;">VALUE 3</span></div>';
var div = document.createElement('div');
div.innerHTML = str;
var spanElems = div.querySelectorAll('span[style]');
var spans = [].map.call(spanElems, function(el) {
return el.textContent.trim();
}).filter(Boolean);
console.log(spans);
You can save the string as a variable, and then use htmlString.match(/VALUE \d+/gmi)
Update:
If the input is a valid HTML string you could parse with this trick (not jQuery or other libs):
var your_string = `<div> </div><div><span style="font family:tahoma,geneva,sans-serif;"><span>VALUE 1</span>fgfgfg</span></div><div><strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div><div><span style="font-family:tahoma,geneva,sans-serif;"> </span>VALUE 3</div>`
var obj_evaluator = document.createElement("div");
obj_evaluator.innerHTML = your_string;
// get the list of div
var list_div = obj_evaluator.getElementsByTagName('div');
var value1 = (list_div[1].firstChild.firstChild.textContent); //value 1
var value2 = (list_div[2].firstChild.firstChild.textContent); //value 2
var value3 = (list_div[3].lastChild.textContent); //value 3
// create an array
var result = [value1,value2,value3]
// print result
console.log(result);
Old answer (wrong because of the VALUE 3,but if all the VALUE are inside the 'span' then this is the right answer! ):
var obj_evaluator = document.createElement("div");
obj_evaluator.innerHTML = your_string;
// debug row
console.log(obj_evaluator);
var list_span = obj_evaluator.getElementsByTagName('span');
for (var i = 0; i < list_span.length; i++) {
console.log(list_span[i].innerHTML);
// here you can print other info of the node
}
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 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)
I have output from a CMS where I need to add a style to a certain character in the string. For instance, my output is:
<div class="date">12 // 14 // 2013</div>
How can I add:
<span style="slashColor">
to the two double slashes so that my result would be:
<div class="date">12 <span class="slashColor">//</span> 14 <span class="slashColor">//</span> 2013</div>
Try this:
var original = $('.date').text();
var new_version = original.split('//').join('<span class="slashColor">//</span>');
$('.date').html(new_version);
Fiddle
If you have many div like the example you posted, you can use this:
$('.date').each(function () {
var original = $(this).text();
var new_version = original.split('//').join('<span class="slashColor">//</span>');
$(this).html(new_version)
});
Fiddle
var elements = document.getElementsByClassName('date');
for (var i = 0, e; e = elements[i++]; ) {
e.innerHTML = e.innerHTML.replace(/\/\//g, '<span class="slashColor">//</span>');
}
or the jQuery way:
$('.date').each(function () {
$(this).html($(this).html().replace(/\/\//g, '<span class="slashColor">//</span>'));
}