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');
}
});
Related
I have list item
<ul class="menu">
<li> LIST 1 </li>
<li> LIST 2 </li>
<li> LIST 3 </li>
</ul>
<div class="append_li"></div>
So suppose when I click on <li>LIST 1</li> remaining li with tags should get appended in div tag but not clicked li, so how to do this using jQuery
You can use jQuery .clone() for this purpose:
$(document).ready(function(){
$('li').click(function(){
//$('.append_li').html('');
$('.append_li').html($('li').not($(this)).clone());
});
});
Working snippet:
$(document).ready(function(){
$('li').click(function(){
//$('.append_li').html('');
$('.append_li').html($('li').not($(this)).clone());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
<li> LIST 1 </li>
<li> LIST 2 </li>
<li> LIST 3 </li>
</ul>
<div class="append_li"></div>
Note: If you want to replace data inside <div> instead of append, then add below line in your code before .clone() line
$('.append_li').html('');
Important:- What every-one talks about invalid HTML, You can overcome to that problem by doing below code:
$(document).ready(function(){
$('li').click(function(){
$('.append_li').html('');
$('.append_li').html($("ul.menu").clone().find('li:eq('+ $(this).index() +')').remove().end());
})
})
Output: http://jsfiddle.net/0mz9s8ng/
You can use like this:
$('.menu li').click(function (){
$(this).siblings('li').clone().appendTo('.append_li')
});
OR Like this
$('.menu li').click(function (){
$(this).siblings('li').appendTo('.append_li')
});
I need to remove the selected class of an <a> and assign it the last <a> instead. Both are nested within individual <li> elements.
Here's an example of the code:
<ul class="tabs clearfix">
<li class="tab">Home</li>
<li class="tab">About</li>
<li class="tab">Profile</li>
<li class="tab">History</li>
<li class="tab">The Beginning of V-Cube</li>
</ul>
How can I achieve this using JavaScript/jQuery? Please advise.
EDIT:
Let's say I don't want to target the last tab specifically. Can the href be used as a selector instead?
EDIT #2:
Thank you so much everyone for the quick response. All your answers were spot on, wish I could mark them all as answers :)
To remove class from an element, use removeClass.
To get the last element, use :last selector or last(). To add new class to element use addClass
$('.selected').removeClass('selected');
$('.tabs li:last a').addClass('selected');
// OR
// $('.tabs li').last().children('a').addClass('selected');
.selected {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="tabs clearfix">
<li class="tab">Home
</li>
<li class="tab">About
</li>
<li class="tab">Profile
</li>
<li class="tab">History
</li>
<li class="tab">The Beginning of V-Cube
</li>
</ul>
Update
Let's say I don't want to target the last tab specifically. Can the href be used as a selector instead?
$('.tabs a[href="#five"]').addClass('selected');
Try this.
$(".tabs li").first().find("a").removeClass("selected");
$(".tabs li").last().find("a").addClass("selected");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="tabs clearfix">
<li class="tab">Home</li>
<li class="tab">About</li>
<li class="tab">Profile</li>
<li class="tab">History</li>
<li class="tab">The Beginning of V-Cube</li>
</ul>
Try this:
$(document).ready(function(){
var classname = $(".tabs li:first-child a").attr("class");
console.log(classname);
$(".tabs li:last-child a").addClass(classname);
$(".tabs li:first-child a").removeClass();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul class="tabs clearfix">
<li class="tab">Home</li>
<li class="tab">About</li>
<li class="tab">Profile</li>
<li class="tab">History</li>
<li class="tab">The Beginning of V-Cube</li>
</ul>
it is quite easy also in vanilla JS:
document.querySelector('.selected').classList.remove('selected');
document.querySelector('.tabs li:last a').classList.add('selected');
If you want to use an arbitrary a and select the attribute href then you should use this selector:
a[href="HREFVALUE"]
$('.clearfix').find('.selected').removeClass('selected');
$('.clearfix').find('li:last').find('a').addClass('selected');
$("a[href$='five']").addClass('bold');
.selected {
color: red
}
.bold {
font-weight: bold
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="tabs clearfix">
<li class="tab">Home
</li>
<li class="tab">About
</li>
<li class="tab">Profile
</li>
<li class="tab">History
</li>
<li class="tab">The Beginning of V-Cube
</li>
</ul>
Just use .removeClass() and .addClass()
.removeClass()
Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
.addClass()
Description: Adds the specified class(es) to each element in the set of matched elements.
I have a menu with li elements, after click on the one of the elements I like to run a function click and display alert with an id of li element.
JS
<script type="text/javascript">
$("#mainmenu li").click(function() {
alert(this.id);
});
</script>
HTML
<div id="menu1">
<ul id="mainmenu">
<li>Choose the first map <i class="arrow"></i>
<ul>
<li>Category 1<i class="arrow"></i>
<ul>
<li class="div1clear" id="firstIDtoDisplay" data-path="contents/work/cycling1.html">% of employees cycling to work</li>
</ul>
</li>
<li>Ethnic maps<i class="arrow"></i>
<ul>
<li class="div1clear" id="secoundIDtoDisplay" data-path="contents/ethnic/white_british1.html">% of White British residents</li>
<li class="div1clear" id="thirdIDtoDisplay" data-path="contents/ethnic/white_tot1.html">% of White residents</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<script type="text/javascript">
$("#mainmenu li").click(function() {
alert(this.id);
});
</script>
<div id="menu1">
<ul id="mainmenu">
<li>Choose the first map <i class="arrow"></i>
<ul>
<li>Category 1<i class="arrow"></i>
<ul>
<li class="div1clear" id="firstIDtoDisplay" data-path="contents/work/cycling1.html">% of employees cycling to work</li>
</ul>
</li>
<li>Ethnic maps<i class="arrow"></i>
<ul>
<li class="div1clear" id="secoundIDtoDisplay" data-path="contents/ethnic/white_british1.html">% of White British residents</li>
<li class="div1clear" id="thirdIDtoDisplay" data-path="contents/ethnic/white_tot1.html">% of White residents</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
Unfortunately after click nothing happens. No errors in console as well.
Probably the mistake is in a JS code, do you have an idea what is an issue?
https://jsfiddle.net/pgsf6fot/
$(document).ready(function() {
$("#mainmenu li").click(function() {
alert( $(this).attr('id') );
});
});
You have 3 options here to solve your issue:
1- Put your JS code after the html element you need to bind too.
2- Use document.ready to make the js code execute after all html render.
3- Use On
use on event for dynamic elements
$(document).ready(function(){
$("#mainmenu").on("click","li",function() {
alert(this.id);
});
});
Might just be a matter of timing, the DOM might not be ready when your JS is executed. So you register the click events on elements that does not exists at that time, because they have not yet been rendered.
Try wrapping with a DOM ready listener (http://api.jquery.com/ready/), this will hold the executing of your JS until the DOM has been rendered.
$(function() {
$("#mainmenu li").click(function() {
alert(this.id);
});
})
$(function(){
$("#mainmenu li ul li ul li").click(function() {
alert(this.id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menu1">
<ul id="mainmenu">
<li>Choose the first map <i class="arrow"></i>
<ul>
<li>Category 1<i class="arrow"></i>
<ul>
<li class="div1clear" id="firstIDtoDisplay" data-path="contents/work/cycling1.html">% of employees cycling to work</li>
</ul>
</li>
<li>Ethnic maps<i class="arrow"></i>
<ul>
<li class="div1clear" id="secoundIDtoDisplay" data-path="contents/ethnic/white_british1.html">% of White British residents</li>
<li class="div1clear" id="thirdIDtoDisplay" data-path="contents/ethnic/white_tot1.html">% of White residents</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
Specify the id attribute of the click li using $(this), and return false to cancel any propagation and the default behaviour of li
<script type="text/javascript">
$("#mainmenu li").click(function(e) {
alert($(this).attr('id'));
return false;
});
</script>
Demo: http://jsfiddle.net/ptx2hwy3/
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");
})
i'm having some trouble.
I'm doing an asp.net mvc3 application and i downloaded some css menu, the thing is i want to keep the menu active after menu tab its clicked and only change when another one is clicked.
here's the code of the menu on _Layout.cshtml
<nav>
<div class="cssmenu">
<ul>
<li class='active'><span>#Html.ActionLink("Início", "Index", "Home")</span></li>
<li><span>#Html.ActionLink("Tarefas Contabilidade", "SelectEmpresa", "Empresa")</span></li>
<li><a href='#'><span>Clientes</span></a>
<ul>
<li><span>#Html.ActionLink("Listar clientes", "ListarEmpresas", "Empresa")</span></li>
</ul>
</li>
<li><a href='#'><span>Balancetes</span></a>
<ul>
<li><span>#Html.ActionLink("Listar registos", "ListaBalancetesPorSalaoMes", "Balancete")</span></li>
</ul>
</li>
<li><span>#Html.ActionLink("Sobre", "About", "Home")</span></li>
</ul>
</div>
</nav>
and i have this script:
<script type="text/javascript">
$("li").click(function () {
$("li").removeClass("active");
$(this).addClass("active");
});
</script>
the first tab that i put there class= "active" works, but the script doesn't seem to work when i click another menu tab, it only shows the first one active
a little help please :)
UPDATED
This is the rendered html:
<nav>
<div class="cssmenu">
<ul>
<li><span>Início</span></li>
<li><span>Tarefas Contabilidade</span></li>
<li><a href='#'><span>Clientes</span></a>
<ul>
<li><span>Listar clientes</span></li>
<li><span>Listar salões</span></li>
<li><span>Gerir empregados</span></li>
<li><span>Novo cliente</span></li>
<li><span>Novo salão</span></li>
</ul>
</li>
<li><a href='#'><span>Balancetes</span></a>
<ul>
<li><span>Listar registos</span></li>
<li><span>Upload novo balancete</span></li>
<li><span>Mapa Resultados/Gráfico</span></li>
<li><span>Mapas Contabilidade/Gestão</span></li>
<li><span>Análise Rentabilidade</span></li>
<li><span>Alterar taxas</span></li>
</ul>
</li>
<li><span>Sobre</span></li>
</ul>
</div>
</nav>
i dont know if i should put the javascript inside the div or something xD
Ty
You can use child selector which selects all direct child elements, Try the following:
$(document).ready(function(){
$(".cssmenu > ul > li").click(function () {
$(this).siblings().removeClass("active");
$(this).addClass("active");
});
})
If you want to select the li tags of the inner ul tags, you can try:
$(document).ready(function() {
$("ul:eq(1) > li").click(function() {
$('ul:eq(1) > li').removeClass("active");
$(this).addClass("active");
});
})
Can you try:
<script type="text/javascript">
$("li a").bind('click', function () {
$("li").removeClass("active");
$(this).addClass("active");
});
</script>
li items are not clickable, so you must bind the click event to a.
try
$("li").click(function (e) {
e.preventDefault();
$(this).siblings().removeClass("active").end().addClass("active");
});