jQuery find element in ul li span - javascript

I have an HTML structure as:
<div title="" class="interestareascategories_chn chzn-container chzn-container-multi">
<ul id="ul_deptType" class="chzn-choices">
<li id="li_dept_1" ver="old" class="search-choice"> <span>DEV</span> <a rel="3" class="search-choice-close" seq="1" href="javascript:void(0)"></a>
</li>
<li id="li_dept_2" ver="old" class="search-choice"><span>QA</span> <a rel="3" class="search-choice-close" seq="2" href="javascript:void(0)"></a>
</li>
<li id="selD7J_chzn_c_3" class="search-choice"><span>sag</span> <a class="search-choice-close" seq="0.19415735425269753" href="javascript:void(0)"></a>
</li>
<li class="search-field"><span contenteditable="true" style="width: 25px;"></span>
</li>
</ul>
</div>
How to get only seq in anchor tag which have rel attribute?

Here's a fairly simple and straightforward answer:
// gets all anchors with attribute rel and place their [seq] values into an array
var values = $.map($('a[rel]'), function(el){
return el.getAttribute('seq');
});
console.log(values); // ["1", "2"]
live code sample

var seq = $("a[rel]").attr("seq");

Try this:
var anchor = $('a[rel][seq]'); // this only targets anchors which have these
// rel and seq attributes.
You can try this:
$('a[rel][seq]').on('click', function () {
alert($(this).attr('seq'));
});
Fiddle

You can use next selector for specific rel value
var seq3 = $("a[rel='3']").attr("seq");
To get sum of all sequences use next:
var sum = 0;
$.each($("a[rel='3']"), function(i, el)
{
sum += el.getAttribute("seq") | 0
})

jQuery(document).ready(function(){{
var check=jQuery(".search-choice a ").attr("rel");
if(check!="undefined")
{
var selVar=jQuery(this).attr("seq");
}
})
you should write a script like this, you can also store all "seq" value in an array.

You you want seq attribute of all anchors that have rel attribute then:
try like this:
$("a.search-choice-close").each(function(){
if($(this).attr('rel')) {
alert($(this).attr('seq'));
}
})
or :
$("a.search-choice-close[rel]").each(function(){
alert($(this).attr('seq'));
})
demo fiddle1
demo fiddle2

You can use something like:
http://jsfiddle.net/U2s7f/1/
$("a[rel]").map(function(i, el) { return $(el).attr("seq"); })

You can use an has attribute selector for rel and the get the value of seq attribute on the selected elements.
Code:
$('a[rel]').each(function(i,e){
console.log($(this).attr('seq'))
});
Demo: http://jsfiddle.net/IrvinDominin/VU3hr/

Related

Compare tag text value with a variable in jquery

I'm trying to compare the value of a tag obtained by query selector in the DOM with a given variable.
So far I've only managed the use of "contains" function, but I need to compare with an equality function.
The DOM element I need to obtain is "span:badge" and the variable to compare is "current_id".
This is the code I need to change:
var $a = $('span.badge:contains("' + current_id + '")').closest('a');
JS:
$(document).ready(function() {
"use strict";
var current_id = window.location.pathname.replace('/califications/','');
if (Number.isInteger(parseInt(current_id, 10))){
var $a = $('span.badge:contains("' + current_id + '")').closest('a');
$($a).addClass('active');
}else{
$('#middle_column > div > h1').html("No kid selected");
}
});
HTML:
<ul class="nav nav-pills flex-column" id="kid_list">
<t t-foreach="kids" t-as="kid">
<li class="nav-item">
<a t-attf-href="/califications/{{kid.id}}" t-attf-class="nav-link"><t t-esc="kid.name"/>
<span class="badge badge-pill float-right" style="display: none;"><t t-esc="kid.id" /></span>
</a>
</li>
</t>
</ul>
Thanks for reading!
To use contains seems right, but you need to do further, because contains also matches aa and ab if you search for a.
const $badges = $('span.badge:contains(`${current_id}`)');
const targetEl = null
$badges.each((i, e)=>{
if(e.text() === current_id){
targetEl = e.
}
})
targetEl should be what you need, or you will also do targetEl.closet("a") if you want to get the a.
You can use the selector which contains t-attf-href attribute ends with the id
$(`[t-attf-href$="${current_id}"]`).addClass('active');
Example:
var id = 'kid_id';
$(`[t-attf-href$="${id}"]`).addClass('active').text('test');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a t-attf-href="/califications/kid_id" t-attf-class="nav-link"><t t-esc="kid.name"/>
<span class="badge badge-pill float-right" style="display: none;"><t t-esc="kid.id" /></span>
</a>
Note: The .text('test') part is just for testing
Solution of the problem found.
var current_id = window.location.pathname.replace('/califications/','');
if (Number.isInteger(parseInt(current_id, 10))){
var $b = $('span.badge');
$b.each(function( index ) {
var badge_value = $( this ).text();
if (badge_value == current_id){
var active_a = $( this ).closest('a');
$(active_a).addClass('active');
}
});
}else{
$('#middle_column > div > h1').html("No kid selected");
}
Thanks for all the responses!

How do I get all the LI UL elements ID value and place them in a JavaScript array?

I have to embed some tracking code on my site. So I have a list of LI elements with an ID value that I want to place inside an array of the snippet. They should be numeric like, 123, 456, etc inside an object. I want to do it in pure JavaScript.
This is my code I have tried. My HTML:
<ul id="itemGrid">
<li class="item" id="1080"> product code </li>
<li class="item" id="1487"> product code </li>
<li class="item" id="1488"> product code </li>
...
</ul>
This is the JavaScript code
// Get all LI items and get the ID of them in the object viewList
var catId = document.getElementById('itemGrid').getElementsByTagName('li');
window.criteo_q = window.criteo_q || [];
window.criteo_q.push(
// SHOULD BE LIKE THIS
// { event: "viewList", item: ["First item id", "Second item id", "Third item id"] }
// My actual code
{ event: "viewList", item: [ catId[].id ] }
);
try this
var lis = document.getElementById('itemGrid').getElementsByTagName('li');
var idArray = [];
for ( var counter = 0; counter < lis.length; counter++)
{
idArray.push( lis[ counter ].id );
}
console.log( idArray );
You can use querySelectorAll to select all the matching elements passed as selector.
The selector '#itemGrid li[id]' will select all the <li> elements inside #itemGrid element having id attribute on it.
The querySelectorAll returns a collection of HTML elements. Iterate over this collection to get the individual element id.
var lis = document.querySelectorAll('#itemGrid li[id]');
var arr = [];
for (var i = 0; i < lis.length; i++) {
arr.push(+lis[i].id);
}
console.log(arr);
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
<ul id="itemGrid">
<li class="item" id="1080">1080</li>
<li class="item" id="1487">1487</li>
<li class="item" id="1488">1488</li>
</ul>
<hr />
You can convert your HTMLCollection to an Array by passing it through slice, and you can then map that array:
catId = Array.prototype.slice.call(catId).map(function(li) { return li.id; });
var catId = document.getElementById('itemGrid').getElementsByTagName('li');
catId = Array.prototype.slice.call(catId).map(function(li) { return li.id; });
document.write(catId);
<ul id="itemGrid">
<li class="item" id="1080"> product code </li>
<li class="item" id="1487"> product code </li>
<li class="item" id="1488"> product code </li>
</ul>
var lis = document.getElementById('itemGrid').getElementsByTagName('li');
var arr = [];
// You need to iterate the list lis
[].forEach.call( lis, function(el){
arr.push( el.id );
});
// Making the object you want
var criteo_q = { event: "viewList", item: arr };
console.log(criteo_q);
To iterate the list of DOM elements, you can also use

Storing only the text of a html list item in a javascript array and not the image src as well

In HTML I have an unordered list with items like
<ul id="sortable">
<li class="ui-state-default"><img src="images/john.jpg">John</li>
<li class="ui-state-default"><img src="images/lisa.jpg">Lisa</li>
<li class="ui-state-default"><img src="images/bill.jpg">Bill</li>
<li class="ui-state-default"><img src="images/sara.jpg">Sara</li>
</ul>
I want to store the names of a selected item in an array and the selection is working fine, the problem is that its also storing the img src as well as the name.
This is my code used to populate the array:
var dataArr = [];
$("#sortable li").each(function(idx, elem) {
dataArr[idx] = $(elem).html();
});
If I were then to output dataArr[0] I would get a return string of "< img src="images/ john.jpg ">John" when I obviously just want "John".
Try this: dataArr[idx] = $(elem).text();
.text() will give you only textual children of the node
var dataArr = [];
$("#sortable li").each(function(idx, elem) {
dataArr[idx] = $(elem).text();
});
Use text() instead of html():
dataArr[idx] = $(elem).text();
Or, to be a little cheaper and avoid the cost of wrapping in a jQuery object each iteration:
dataArr[idx] = elem.textContent || elem.innerText;
References:
text().

jQuery click function for <ul><li> elements

I have a unordered list looking like this:
<ul id="frozen" data-name="nameOfSelect" class="tagit">
<li class="tagit-choice" tagvalue="2" style="padding-right: 4px;" id="tag-2">
<div class="tagit-label" data-value="2">kázeň</div>
</li>
<li class="tagit-choice" tagvalue="1" style="padding-right: 4px;" id="tag-1">
<div class="tagit-label" data-value="1">žalmxxxx</div>
</li>
</ul>
I need to bind an click function to all of them and get the data of the id="tag-1" to be used in the function.
I have tried this:
$('#[id|="tag"]').each(function(){
var tag = this.attr('id');
var tagID = tag.replace('tag-','');
this.click(function (){
alert('index.php?s=taglist&tag=' + tagID);
//window.location = string;
});
});
However, for some reason it seems that this approach is wrong for the <li> element as I am having problems with the selector (it seems). Maybe I am also missing something stupid... Any ideas?
No need for a loop, jQuery does this internally, and this is a native DOM element, which has an id property, but no attr() method :
$('[id^="tag-"]').on('click', function() {
var tag = this.id,
tagID = tag.replace('tag-', '');
alert('index.php?s=taglist&tag=' + tagID);
});

get an array of data-val values from a list of elements of a certain css class

I would like to get an array of the values from the data-val attributes of .my-li elements
<ul id="stuff">
<li class='my-li' data-val='1'>
<li class='my-li' data-val='2'>
<li class='my-li' data-val='3'>
<li class='my-li' data-val='4'>
<li class='my-li' data-val='5'>
<ul>
here the result should be [1,2,3,4,5];
anybody knows a good way of doing this ?
Try:
var foo = $('#stuff .my-li').map(function () {
return $(this).data('val');
});
try this simple one.
var array = [];
$('.my-li').each(function(){
array.push($(this).attr('data-val'));
});
alert(array);
fiddle : http://jsfiddle.net/pp5pw/
var foo = $('#stuff .my-li').map(function () {
return $(this).attr('data-val');
});
console.log(foo[0])
jsfiddle goes to http://jsfiddle.net/granjoy/KxQAr/

Categories