find <ul> id based on text of <li> - javascript

I have li with unique text and i want to get the id on that text.
<ul id="test1">
<li>My Link</li>
</ul>
<ul id="test2">
<li>Test Link</li>
</ul>
I want to get the UL id, whose li anchor tag onclick function contains text is users.

You can use filter to do this:
var $usersUl = $('a').filter(function() {
return $(this).attr('onclick').indexOf('users') != -1;
}).closest('ul');
Example fiddle
It should be noted however that having your UI rely on a parameter in a JS function call is a little unsightly, if not verging on a hack. If you can, change the HTML to include some data attributes and filter by those:
<ul id="test1">
<li>My Link</li>
</ul>
<ul id="test2">
<li>Test Link</li>
</ul>
var $users = $('a').filter(function() {
return $(this).data('users');
}).closest('ul');

Using the attribute contains selector:
Fiddle
var id = $('ul > li > a[onclick*="\'users\'"]').closest('ul').attr('id');
Or to include the function name as well:
var id = $('ul > li > a[onclick="myfunction(\'users\')"]').closest('ul').attr('id');

I wouldn't use an onclick in this case, try something like this:
<ul id="test1">
<li>My Link</li>
</ul>
<ul id="test2">
<li>Test Link</li>
</ul>
Then jQuery:
$("li").click(function() {
parent = $(this).parent(); // your UL element
value = $(this).data('value'); // your parameter, you can use it now
// Rest of your function right here
});

Try this:
$('a[onclick*="users"]').each(function() {
console.log($(this).text());
});
DEMO

Try this:
$(document).ready(function(){
$('li a').on('click', function(){
alert($(this).closest('ul').prop('id'));
});
});
Here is my fiddle example http://jsfiddle.net/58CTf/3/

<script>
function myfunction(param, event) {
console.log(event.target.parentElement.parentElement.id);
}
</script>

Pass the current object in event handler and use to get the id of parent ul using closest(), onclick="myfunction(this,'users')"
Live Demo
HTML
<ul id="test1">
<li>My Link</li>
</ul>
<ul id="test2">
<li>Test Link</li>
</ul>
Javascript
function myfunction(obj, parm)
{
alert($(obj).closest('ul').attr('id'));
}

here it is:
$('ul a').click(function(){ // click event for anchor tag which is inside ul
if($(this).indexOf("users") == -1) // check if text contains users
{
console.log($(this).parent("ul").attr("id")); // get its parent ul id
}
})

try this this works great(use parent function)
$(function(){
$("ul li").find("a:contains(Link)").parent().parent().attr("id");
})

Related

How to get selected dropdown value

I have a dropdown menu like this:
<ul class="dropdown-menu" id="Appdropdown">
</ul>
which I am populating dynamically using this code:
for (var i = 0; i < arrdropdownMenuItems.length; i++)
{
dropdownMenuhtml += '<li>' + arrdropdownMenuItems[i] + '</li>';
}
$('#ApplicationNames').css("visibility", "visible");
$('#Appdropdown').append(dropdownMenuhtml);
And now when the user clicks on an <a>, I need to get the selected dropdown value. - I've tried this:
$('ul#Appdropdown').click(function ()
{
var cache = $('.btn-primary').children();
$('.btn-primary').text($(this).text()).append(cache);
}
but it's not giving the selected value from the dropdown.
Though it is not correct to listen click on parent element rather than child event, still your requirement can be accomplished using following code.
Basically you can fetch actual element that is clicked from event data that is passed by click event by default.
$('ul#Appdropdown').click(function (ev) {
var a = $(ev.target);
if(a.is("a"))
$('#selectedText').text($(a).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-menu" id ="Appdropdown">
<li>Test A</li>
<li>Test B</li>
<li>Test C</li>
<li>Test D</li>
<li>Test E</li>
</ul>
<div id="selectedText"></div>
Several things missing in you code.
First ensure you are writing entire piece of code in document.ready,then make sure you fire the click event on li click instead of ul.Next as you are creating the control dynamically use .on.
$(document).ready(function() {
$('ul#Appdropdownli li').on('click', function() {
var selctedtext = $(this).find('a').html();
console.log(selctedtext);
});
});
You can get the selected drop-down value using the following code.
Please note, a reference of #selectedText is kept outside the event handler for a so no additional dom query is necessary.
var selectedText = $('#selectedText');
$('#Appdropdown > li > a').on('click', function(event) {
selectedText.text($(event.target).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-menu" id="Appdropdown">
<li>Test A</li>
<li>Test B</li>
<li>Test C</li>
<li>Test D</li>
<li>Test E</li>
</ul>
<div id="selectedText"></div>
You could add a class/id to each option, and then add an event listener to that class, like this:
Html:
<ul class="dropdown-menu">
<li><button class="dropdown-option">Option 1</button></li>
<li><button class="dropdown-option">Option 2</button></li>
<li><button class="dropdown-option">Option 3</button></li>
<li><button class="dropdown-option">Option 4</button></li>
<li><button class="dropdown-option">Option 5</button></li>
</ul>
JavaScript:
$('.dropdown-option').click(function () {
console.log($(this).html());
});
$(this) is the actual element that is being clicked.
Pretty simple solution, which could also easily be converted to vanilla javascript.
JSfiddle example

Need to click Each li Element without affecting parent

I have HTML Structure like
<ul>
<li><a></a>
<ul>
<li><a></a>
<ul>
<li><a></a>
<ul>
<li><a></a></li>
</ul>
</li>
</ul>
</li>
</ul>
I want to add 'active' class for relevant 'a' Element when corresponding li clicked.
$('#a').on('click', function(){
$('a', this).addClass('active');
});
<ul>
<li id="a"><a></a>
<ul>
<li id="b"><a></a>
<ul>
<li id="c"><a></a>
<ul>
<li id="d"><a></a></li>
</ul>
</li>
</ul>
</li>
</ul>
Use children() method, since you only want to select the direct child
$('li').click(function(){
$(this).children('a').addClass('active')
})
or use > to select direct child
$('li').click(function(){
$('>a', this).addClass('active')
})
A delegate click handler would most likely solve your problem best.
$('ul.master').on('click', 'li', function (evt) {
evt.stopPropagation();
// I added this line to remove active class from all other a tags
$(this).parents('ul.master').find('a').removeClass('active');
$(this).children('a').addClass('active');
});
See this jsfiddle
You could work on the <a> tag directly to capture the click for changing the active class. If you need to work directly with the <li> You can attach another handler.
$('a').click(function(evt){
$(this).addClass('active');
});
$('li').click(clickHandler);
You mean something like this?
$('li').on('click', function(){
$('a', this).addClass('active');
});
just target the li a directly:
$('li a').on('click', function(){
$(this).addClass('active')
});
$('li').on('click', function(){
$(this).closest('a').addClass('active');
});
Get first child using :first (if you have only one anchor per li) the use addclass method to assign class
I fixed your HTML:
<ul>
<li>
<a>A</a>
<ul>
<li>
<a>B</a>
<ul>
<li>
<a>C</a>
<ul>
<li>
<a>D</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
jQuery + JS code:
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script type="text/javascript">
$('a').click(function(){
$(this).parent('li').addClass('active')
})</script>
$(document).on('click', 'a', function(){
if($(this).parent('li').length) {
$(this).parent('li').addClass('active');
}
});

Jquery If class has matching ID then hide

What I'm trying to do here is check if an element has the same id as a class in another element if so hide the matching id.
So far this is what I have came up with but it doesn't seem to kick.
JSfiddle
var theid = $('#me li').attr('id');
if ($('#you li').hasClass( theid )) {
$('#me li#'+theid+'').hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<ul id="me">
<li id="num-0">iam 1</li>
<li id="num-1">ieam 2 & should be hidden</li>
<li id="num-2">iam 3</li>
<li id="num-3">iam 4</li>
<li id="num-4">ieam 5 & should be hidden</li>
<li id="num-5">iam 6</li>
</ul>
<ul id="you">
<li class="num-1">iam killer</li>
<li class="num-4">iam killer</li>
</ul>
Use each() to loop over all the li elements inside the #you
hide() the elements having the id same as the class of current element in loop.
$('#you li').each(function() {
$('#' + $(this).attr('class')).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<ul id="me">
<li id="num-0">iam 1</li>
<li id="num-1">ieam 2</li>
<li id="num-2">iam 3 & should be hidden</li>
<li id="num-3">iam 4</li>
<li id="num-4">ieam 5 & should be hidden</li>
<li id="num-5">iam 6</li>
</ul>
<ul id="you">
<li class="num-2">iam killer</li>
<li class="num-4">iam killer</li>
</ul>
Demo
When you use the .attr() method on a jQuery object that contains multiple elements, it just returns the attribute from the first element. You need to loop over each element and check them one at a time.
It is, however, OK for your purposes to use .hasClass() on the set of all of the #you elements, because .hasClass() will return true if any of the elements in the set has that class. So:
var you = $('#you li');
$('#me li').each(function() {
if (you.hasClass(this.id))
$(this).hide();
});
Note that I'm keeping a reference to the $('#you li') jQuery object in the variable you to save selecting those elements again every time in the loop.
Demo: https://jsfiddle.net/d65sz4js/2/
Try this for your jquery:
$(function() {
$("#you li").each(function(){
var theid = $(this).attr('class');
$('#'+theid).hide();
});
});
Demo: https://jsfiddle.net/nkem9o7o/
You could filter the #me li's, returning elements where their id exists as a class in #you li's, then just hide them. This would also work for multiple classes:
$('#me li').filter(function() {
return $('#you').has('.' + this.id).length;
}).hide();
Here's a fiddle

Select jquery elements except specific children

This is a simple question, but, I haven't found a clear answer in any of the question that I found. I modified a JSFiddle for my specific question.
I got this tiny code:
<ul>
<li id='one'>Element 1</li>
<li id='two'>Element 2</li>
<li id='three'>Element 3</li>
<li id='four'>Element 4</li>
<li id='five'>Element 5</li>
</ul>
and this script should return the ul element excepting the first li:
$(function(){
$("ul").not($('#one'))
});
Instead, it removes every li. What have I done wrong?
EDIT: In others words, I would like a selector which selects this, without removing the actual element (= inside a variable)
<ul>
<li id='two'>Element 2</li>
<li id='three'>Element 3</li>
<li id='four'>Element 4</li>
<li id='five'>Element 5</li>
</ul>
FIDDLE: http://jsfiddle.net/LVUMs/13/
Use
$("ul li").not($('#one')).remove();
DEMO
OR
$("ul li:not(#one)").remove();
DEMO 2
EDIT
You need
var ulexceptOneLi = $("ul li:not(#one)");
or
var ulexceptOneLi = $("ul li").not($('#one'));
Try this code:
Fiddle
$(function(){
$("ul>li").not($('#one')).empty();
});
Assuming you meant to keep the ul in play:
$("ul li#one").remove();
Here's a fiddle...
If you're wanting to return a ul element with the removed element inside, try this:
function do_crazy_thing(){
var removed = $("ul li#one").remove();
return $('<ul></ul>').append(removed);
}
do_crazy_thing();
Here's another fiddle...
Here's how you would then append your new ul element to the body...
Demo Fiddle
According to your question, your expected output is :
<ul>
<li id='two'>Element 2</li>
<li id='three'>Element 3</li>
<li id='four'>Element 4</li>
<li id='five'>Element 5</li>
</ul>
Check the demo.
Edit :
$(function(){
var removed = $("ul li:not(#one)");
});
OR
var op = $("ul :not(#one)");
Please try below JS code
$(function(){
var test= $("ul li").remove("#one");
});

How to Select Element That Does Not have Specific Class

I'm wondering how to select an element that does not have a specific class using JavaScript, not jQuery.
For example, I have this list:
<ul id="tasks">
<li class="completed selected">One Task</li>
<li>Two Task</li>
</ul>
and I select the completed task by:
var completeTask = document.querySelector("li.completed.selected");
But then I'm not sure how to select the list item that does not have those classes.
This selects the second LI element.
document.querySelector("li:not([class])")
or
document.querySelector("li:not(.completed):not(.selected)")
Example:
// select li which doesn't have a 'class' attribute...
console.log(document.querySelector("li:not([class])"))
// select li which doesn't have a '.completed' and a '.selected' class...
console.log(document.querySelector("li:not(.completed):not(.selected)"))
 <ul id="tasks">
<li class="completed selected">One Task</li>
<li>Two Task</li>
</ul>
To select the <li> that has not completed nor selected class:
document.querySelector("li:not(.completed):not(.selected)");
Fiddle
http://jsfiddle.net/Z8djF/
You can try the :not() selector
var completeTask = document.querySelector("li:not(.completed):not(.selected)");
http://jsfiddle.net/UM3j5/
The :not(*selector*) selector also accepts commas (so does querySelectorAll()) https://developer.mozilla.org/en-US/docs/Web/CSS/:not#syntax:
let plainElements = document.querySelectorAll( ':not( .completed, .in-progress ) ');
plainElements.forEach( ( item ) => { item.style.color = 'red'; } );
li { color: green; }
<ul id="tasks">
<li class="completed selected">Task 1</li>
<li>Task 2</li>
<li class="in-progress">Task 3</li>
</ul>
document.querySelectorAll('[wf-body=details] input:not(.switch):not(.btn)').forEach(function(e){
// do whatever you want. with 'e' as element :P
});
Try getting an array of the parent's children instead:
var completeTask = document.querySelector("#tasks").childNodes;
Then loop/search them as necessary.

Categories