I have an html list something like this:
<li id="tag">red</li>
<li id="tag">yellow</li>
<li id="tag">blue</li>
How can I get the content of these li tags using jQuery?
For example;
$tags = red, yellow, blue
You can use jQuery.map()
Live Demo
texts = $('li').map(function(){
return $(this).text();
}).get().join(',');
var $tags = $("li").map(function(){
return $(this).text();
}).get().join(",");
Here, have a fiddle: http://jsfiddle.net/KTted/2/
First, you should change your id="tag" to class="tag", as you can't have multiple elements with the same id.
You can build an array of the values:
var content = [];
$("li").each(function (element) {
content.push[$(element).text()];
});
Or as others have pointed out, you can use map:
var content = $("li").map(function() {
return $(this).text();
}).get().join(",");
Related
There are href links on the page, its text is not complete. for example page is showing link text as "link1" however the correct text should be like "link1 - Module33". Both page and actual texts starts with same text (in this example both will starts with "link1").
I am getting actual text from JSON object from java session and comparing. If JSON text starts with page text (that means JSON text "link1 - Module33" startsWith "link1" (page text), then update "link1" to "link1 - Module33".
Page has below code to show the links
<div class="display_links">
<ul id="accounts_links_container">
<li id="accounts_mb_2_id"><a href="javascript:void(0)" class="linksmall"
id="accounts_mb_2_a"> link1 </a></li>
<li id="accounts_mb_11_id"><a href="javascript:void(0)" class="linksmall"
id="accounts_mb_11_a"> link2 </a></li>
.
.
.
// more links
</ul>
</div>
Note : li id is not static its different for each page text, however ul id is static.
I am reading correct & full link text from JSON object (from java session) as below
var sessionValue = <%= json %>; // taken from String array
and reading page text as below :-
$('.display_links li').each(function() { pageValue.push($(this).text()) });
sessionValue has correct updated text and pageValue has partial texts. I am comparing using below code
for(var s=0; s<pageValue.length; s++) {
var pageLen = $.trim(pageValue[s]).length;
for(var w=0; w<sessionValue.length; w++) {
var sesstionLen = $.trim(sessionValue[w]).length;
var newV = sessionValue[w].substring(0, pageLen);
if($.trim(newV)==$.trim(pageValue[s])){
**// UPDATING VALUES AS BELOW**
pageValue[s]=sessionValue[w];
}
}
}
I am trying to update page value text to session value text as pageValue[s]=sessionValue[w]; (in above code) but its not actually updating the values. Sorry for the poor comparing text logic.
Please help, how to update it dynamically in the loop after comparing to make sure I am updating the correct link text.
pageValue[s]=sessionValue[w]; just updates the array; it has no effect whatsoever on the li's text.
If you want to update the li's text, you need to do that in your each. Here's an example doing that, and taking a slightly more efficient approach to the comparison:
$('.display_links li a').each(function() {
var $this = $(this);
var text = $.trim($this.text());
var textLen = text.length;
for (var w = 0; w < sessionValue.length; ++w) {
var sessionText = $.trim(sessionValue[w]);
if (sessionText.substring(0, textLen) == text) {
text = sessionText;
$this.text(text);
break; // Found it, so we stop
}
}
pageValue.push(text); // If you want it for something
});
I think it's cleaner to just select the elements you care about (in this case the anchor tags) and then use built-in functionality to compare rather than reimplementing a startsWith function.
var sessionValue = ['link1 - Module33', 'link2 - foobar'];
$('.display_links li a').each(function() {
var $this = $(this);
var text = $this.text().trim();
sessionValue.forEach(function(sessionValue) {
if (sessionValue.startsWith(text)) {
$this.text(sessionValue);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="display_links">
<ul id="accounts_links_container">
<li id="accounts_mb_2_id"> link1 </li>
<li id="accounts_mb_11_id"> link2 </li>
</ul>
</div>
The result of $(this).text() is a primitive string, not a reference to the textNode of the element. It doesn't matter if you update pageValue, because it is not related to the original element.
Instead of pushing the strings to an array to process, you can stay inside the $.each() loop and still have access to the elements, which is needed to update the text. Something like this:
$('.display_links li').each(function() {
var $li = $(this);
var liText = $.trim($li.text());
var liLen = liText.length;
for(var w = 0; w < sessionValue.length; w++) {
var sessionLen = $.trim(sessionValue[w]).length;
var newV = sessionValue[w].substring(0, liLen);
if ($.trim(newV) === liText) {
**// UPDATING VALUES AS BELOW**
$li.text(sessionValue[w]);
}
}
});
I am a noob and thought I would take a shot at this.
Here is my approach although the sessionValue array is a bit foggy to me. Is the length undetermined?
I declared var's outside of the loop for better performance so they are not declared over and over.
Iterate through elements passing each value through Compare function and returning the correct value and update immediately after all conditions are satisfied.
var i = 0;
$('.display_links li a').each(function(i) {
$(this).text(Compare($(this).text(), sessionValue[i]));
i++;
});
var Compare;
var update;
Compare = function(val1, val2) {
// Check if val1 does not equal val2 and see if val2 exists(both must be true) then update.
if(!val1 === val2 || val2) {
update = val2
}
return update;
}
The gist of it is that I have a dynamically generated drop down based off an array in JQuery. I have a text field next to it that should output an answer based on what was selected in the array.
<ul>
<li>
Vendor Contacts
<ul class="vendor_list">
</ul>
</li>
<input id="vendor_contact" type="text" />
</ul>
This is the HTML that I set up and here's the Javascript:
var vendors = ['vendor1, vendor2, vendor3'];
var contact_info = ['email1','email2','email3']
var vList = $('ul.vendor_list');
$.each(vendors, function (i)
{
var li = $('<li/>')
.addClass('menu_item')
.attr('role', 'menuitem')
.appendTo(vList);
var aaa = $('<a/>')
.addClass('vendors')
.text(vendors[i])
.appendTo(li);
});
What I think is the next step is:
$("#vendor_list").on('click', '.vendors', function () {
$("vendor_contact")val($(contact_info[i]))
Needless to say, I mind's pretty warped around this one. I'm starting to get into jQuery and just want to see how I can fill the text box in.
First, you have missing quotation marks in your vendors array:
var vendors = ['vendor1', 'vendor2', 'vendor3'];
Next, you should use class selector, not id on your .vendor_list element:
$(".vendor_list").on('click', '.vendors', function () {
// ...
Next, missing # sign, as you're selecting the element by its id:
$("#vendor_contact")val(//...
(by $("vendor_contact") you're trying to select a not existing tag <vendor_contact>)
Last thing, use something like data attribute to determine the actual selection:
$.each(vendors, function(i){
var li = $('<li/>')
.addClass('menu_item')
.attr('role', 'menuitem')
.appendTo(vList);
var aaa = $('<a/>')
.addClass('vendors')
.text(vendors[i])
// add 'data-id' attr:
.data('id', i)
.appendTo(li);
});
final JS:
$(".vendor_list").on('click', '.vendors', function () {
$("#vendor_contact").val(contact_info[$(this).data('id')]);
});
JSFiddle Demo
what's the best way to remove the grapes duplicate from this? there are tons of ways of removing duplicates from simple arrays, but this would be an array with html elements
<div class="fruit">
grapes
</div>
<div class="fruit">
bananas
</div>
<div class="fruit">
grapes
</div>
I've tried using something like
$('.fruit').each(function () {
$('.fruit:has("' + $(this).text() + '"):gt(0)').remove();
});
Try
var obj = {};
$('.fruit').each(function(){
var text = $.trim($(this).text());
if(obj[text]){
$(this).remove();
} else {
obj[text] = true;
}
})
Demo: Fiddle
:has expects an element selector while :contains takes a string
see http://api.jquery.com/contains-selector/
so this should do the trick:
$('.fruit').each(function () {
$('.fruit:contains("' + $(this).text() + '"):gt(0)').remove();
});
fiddle: http://jsfiddle.net/kam7E/
http://jsfiddle.net/S3wXM/1/
Assuming that you wish to remove only one of the duplicates.
Using contains, like the answer above but implementation is slightly different.
$($("div:contains('grapes')")[0]).remove();
http://api.jquery.com/jQuery.unique/ - This also might be of use to you.
var uniqueFruits = [];
$(".fruit").each(function(i,e){
var thisFruit = $.trim($(e).text());
if(uniqueFruits.indexOf(thisFruit) == -1)
uniqueFruits.push(thisFruit);
else
$(e).remove();
});
http://jsfiddle.net/a7E9e/
jsFiddle here: http://jsfiddle.net/THEtheChad/UKRwf/
var found = {};
var $unique_fruits = $('.fruit').filter(function(){
var data = this.innerHTML.trim();
if(!found.hasOwnProperty(data)) return found[data] = true;
});
Here is the working fiddle for this:-
http://jsfiddle.net/HwUUs/1/
$( "div:contains('grapes')" ).remove();
I have few uploaded images in one div and I want to move them to another div and update the database table. For that I need the id's of the images selected and the name of the div where I want to move.
I have the id of the selected image using the check box but I am not sure how can I get all id's in the end .
function MoveImages(){
for ( var i = 0; i < $(".ct input[type=checkbox]:checked").length; i++) {
var element = $(".ct input[type=checkbox]:checked")[i];
var parent = element.parentNode;
var id = parent.getAttribute('id');
}
}
how can I get all the id's in the end ?
This is how my class looks like.
<div class="ct" id="559429bc0d559162552c9728">
<input type="checkbox" class="remove">
<img src="/image?id=c9728" data-src="random.JPG" id="previewImagec9728">
</div>
the move function should return all the id's.
With a bit of JQuery's $.each, substring, and JS array methods, you can grab the raw IDs and put them in an array like so:
var ids = [];
//For each element that matches ".ct input[type=checkbox]:checked".
$.each($('.ct input[type=checkbox]:checked'), function() {
//Find the image element, get the id value, and strip the first 12 characters.
var id = $(this).find('img').attr('id').substring(12);
//Put ID in array.
ids.push(id);
});
Use $.map():
var yourIds = $(".ct input[type=checkbox]:checked").map(function(){
return $(this).parent().attr('id');
});
Try jquery's each:
$('.ct').each(function() {
var id = $(this);
})
use :has and .map
$('.ct:has(:checked)').toArray().map(function(element, index) { return element.id })
or
$('.ct:has(:checked)').map(function(index, element) { return element.id }).toArray()
in both cases .toArray() is to get a normal array instead of a jquery array
I have a problem I want to solve with jQuery. In a list, I want to check if two items have the same text, and if so I want to delete the second one.
I am not really sure how to go about it.
The markup is simple, kinda like this
<ul>
<li>Text1</li>
<li>Text2</li>
<li>Text1</li>
<li>Text3</li>
<li>Text3</li>
<li>Text4</li>
<ul>
I cannot use an active/inactive class because this list is dynamic and I don't know in advance how it's going to be populated.
Any idea?
$.inArray for a tmp array would work.
$(document).ready(function(){
var tmparr = [];
$('.list li').each(function(i,item){
if($.inArray($(this).text(), tmparr) >= 0){
$(this).remove();
}else{
tmparr.push($(this).text());
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
<li>Text1</li>
<li>Text2</li>
<li>Text1</li>
<li>Text3</li>
<li>Text3</li>
<li>Text4</li>
<ul>
You can achieve this e.g. like this:
var unique = {};
$('li').each(function() {
var txt = $(this).text();
if (unique[txt])
$(this).remove();
else
unique[txt] = true;
});
Fiddle
As explanation: unique is initialized as object. While each() iterates over all li elements, the if (unique[txt]) is true in case it was previously set to true for the text of the li currently processed. In this case the current li will be removed. If not, unique[txt] for the text of the current li is set to true and added to unique. As it might not be clear what unique finally contains: { Text1=true, Text2=true, Text3=true, Text4=true }
You will need to iterate over your li elements and store their text in an array. If the text for the ith element is already in the array, skip it. Once you have an array of unique text strings, remove all li elements and generate new ones from the information in your array.
http://jsfiddle.net/k255o52e/1/
$('ul li').each(function () {
var txt = $(this).text();
// finds all LI that contain the same text
// excludes the first element
var $li = $('li:contains("' + txt + '"):not(:first)');
// and removes the other
$li.remove();
})
UPDATE:
$('ul li').each(function () {
var txt = $(this).text();
var $li = $('li:contains("' + txt + '"):not(:first)').filter(function(index)
{
return $(this).text() === txt;
});
$li.remove();
})