I want add class to clicked li and delete other li class
<ul>
<li onclick="s()"><span>خانه</span></li>
<li onclick="s()"><span>سفارش</span></li>
<li onclick="s()" class="selected"><span>آپلود</span></li>
<li onclick="s()"><span>درباره ما</span></li>
<li onclick="s()"><span>تنظیمات</span></li>
</ul>
I can do it with jquery but now i want do this with javascript?
Don't use inline click handlers. Instead, attach a handler from JavaScript.
<ul id="myUL"> <!-- This is just for example, to make it easier to select -->
<li><span>خانه</span></li>
<li><span>سفارش</span></li>
<li class="selected"><span>آپلود</span></li>
<li><span>درباره ما</span></li>
<li><span>تنظیمات</span></li>
</ul>
Then, in JavaScript:
var myUL = document.querySelector('#myUL');
// Attach one event listener on the parent, instead of one for each element.
// It's more performant and will work with dynamically added entries!
myUL.addEventListener('click', function(event) {
// Here, event.target is the actual event clicked.
// Remove class from selected one.
document.querySelector('#myUL .selected').classList.remove('selected');
// And add it to the current one
event.target.classList.add('selected');
});
Working Example
This is a quick fix and this way is not recommended. But in your case, you need to use this way:
function s (which) {
document.querySelectorAll(".clicked")[0].classList.remove("selected");
which.classList.add("selected");
}
And change the call this way:
<ul>
<li onclick="s(this)"><span>خانه</span></li>
<li onclick="s(this)"><span>سفارش</span></li>
<li onclick="s(this)" class="selected"><span>آپلود</span></li>
<li onclick="s(this)"><span>درباره ما</span></li>
<li onclick="s(this)"><span>تنظیمات</span></li>
</ul>
The right way is to use eventListeners and bind the events to an ID.
var list = document.querySelector('#menu');
list.addEventListener('click', function(event) {
list.querySelector('.selected').classList.remove('selected');
event.target.classList.add('selected');
});
And add the ID to the <ul>:
<ul id="menu">
<li>خانه</li>
<li>سفارش</li>
<li class="selected">آپلود</li>
<li>درباره ما</li>
<li>تنظیمات</li>
</ul>
Related
const dropdownmenu = document.querySelector(".dropdownmenu")
dropdownmenu.forEach(element => {
console.log(element.classname)
});
Question is How can i get classname of element of foreach in Javascript ?
Two issues:
document.querySelector only selects one element - the first element that matches the specified selector. You should use document.querySelectorAll to grab an array of elements.
.classname should be camelcased -> .className
I'm assuming you are trying to grab the elements inside of the dropdown menu. Here's how you'd do that:
<ul class="dropdown-menu">
<li class="item">item1</li>
<li class="item">item2</li>
<li class="item">item3</li>
</ul>
<script>
const menu = document.querySelector('.dropdown-menu')
for (const elem of menu.querySelectorAll('.item')) {
console.log(elem.className);
}
</script>
If you're trying to listen for events on the dropdown menu for all of the items, try putting the event listener right on the parent and using e.target to target the clicked child.
<p>Click the items</p>
<ul class="dropdown-menu">
<li class="item">item1</li>
<li class="item">item2</li>
<li class="item">item3</li>
</ul>
<script>
const menu = document.querySelector('.dropdown-menu');
menu.addEventListener('click', (e) => {
console.log(e.target.textContent);
});
</script>
How to convert this code into event delegation?
This is HTML code
<ul id="todo-app">
<li class="item">Walk the dog</li>
<li class="item">Pay bills</li>
<li class="item">Make dinner</li>
<li class="item">Code for one hour</li>
</ul>
Javascript code
document.addEventListener('DOMContentLoaded', function() {
let app = document.getElementById('todo-app');
let items = app.getElementsByClassName('item');
// attach event listener to each item
for (let item of items) {
item.addEventListener('click', function() {
alert('you clicked on item: ' + item.innerHTML);
});
}
});
Above code technically work, the problem is that, attaching an event listener to every single item individually.
Using above code application could end up with hundreds of event listeners, the more efficient solution would be to actually attach one event listener to the whole container, and then be able to access each item when it’s actually clicked.
So , how to make this code using event delegation?
All you need to know to achieve what you want in pure Js is in this post Event Delegation - David Walsh
In your case would be:
document.getElementById("todo-app").addEventListener("click",function(e) {
// e.target was the clicked element
if (e.target && e.target.matches("li.item")) {
console.log("List item clicked!");
}
});
<ul id="todo-app">
<li class="item">Walk the dog</li>
<li class="item">Pay bills</li>
<li class="item">Make dinner</li>
<li class="item">Code for one hour</li>
</ul>
Hope it helps!
how about this, binding event on ul
document.addEventListener('DOMContentLoaded', function() {
let app = document.getElementById('todo-app');
let items = app.getElementsByClassName('item');
app.onclick = function(e){
alert('you clicked on item: ' + e.target.innerHTML);
}
});
<ul id="todo-app">
<li class="item">Walk the dog</li>
<li class="item">Pay bills</li>
<li class="item">Make dinner</li>
<li class="item">Code for one hour</li>
</ul>
jQuery is really comfortable to use for event delegation situation. You just have to attach your listener to the parent element, and specify the child type element on which the event will be delegated :
$( "#todo-app" ).on( "click", "li", function( event ) {
event.preventDefault();
console.log( $( this ).text() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="todo-app">
<li class="item">Walk the dog</li>
<li class="item">Pay bills</li>
<li class="item">Make dinner</li>
<li class="item">Code for one hour</li>
</ul>
Html
<ul>
<li>
</li>
<li>
</li>
<li>
</li>
<li>
</li>
<li>
</li>
</ul>
My app got a list of things then after 5secs. it will automatically go to the next li.
but that is not the problem. the problem is with the click function I want to know the data-id of the li.
According to the OP's comments
Remove the onclick attribute.
Bind the click event using jQuery.
Use closest('li') to get the parent of your links.
function clickFunction(e) {
e.preventDefault(); // This is to prevent the execution of your links!
console.log($(this).closest('li').data('id'));
}
$('a').click(clickFunction);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-id="1">
1
</li>
<li data-id="2">
2
</li>
<li data-id="3">
3
</li>
<li data-id="4">
4
</li>
<li data-id="5">
5
</li>
</ul>
(1) Remove onclick attribute.
(2) Attach a .click handler to all your links
$(function () {
// attach an onclick event handler to your links
$('li a[data-id]').click(function (e) {
// prevent the link from going anywhere
e.preventDefault();
// get the parent li
var li = $(this).closest('li');
// get next li's link data id
console.log(li.next('li').find('a').data('id'));
});
});
I would like to add and immediately remove class ".current" for all page elements with class ".chrome" after click at menu item with ".menu-item" class.
<ul id="navigation">
<li class="menu-item">1</li>
<li class="menu-item">2</li>
<li class="menu-item">3</li>
<li class="menu-item">4</li>
<li class="menu-item">5</li>
<li class="menu-item">6</li>
<li class="menu-item">7</li>
<li class="menu-item">8</li>
<li class="menu-item">9</li>
</ul>
Please look at addClass() and removeClass() from the jQuery documentation. To add a class, and then immediately remove it, you can use the following:
$('.menu-item').on('click', function() {
$('.chrome').addClass('current').removeClass('current');
});
This is what i can think of reading what you've asked for.
to add class to everything after click
$(".menu-item").on("click",function(){
//this is to add to all
$("*").addClass("current");
//this is to add to all with class chrome
$(".chrome").addClass("current");
});
to remove all
$(".menu-item").on("click",function(){
//this is to remove all
$("*").removeClass("current");
//this is to remove classes all from .chrome
$(".chrome").removeClass("current");
});
both
$(".menu-item").on("click",function(){
//add remove all
$("*")$("*").addClass("current").removeClass("current");
//add remove all from .chrome
$(".chrome")$("*").addClass("current").removeClass("current");
});
I have done coding the first part HTML then JavaScript/JQuery. Now I want to surround the final common list with a UL need to be done using JavaScript/JQuery. So the final common list will be surrounded by two UL instead of one. Eg
Final Outcome
<ul id="CommonLister">
<ul> <!--Need to add this-->
<li class="columnItem">John</li>
<li class="columnItem">Mark</li>
</ul><!--Need to add this-->
</ul>
Current Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul id="listOne">
<li class="columnItem">John</li><!--will be removed and put under CommonLister-->
<li class="columnItem">James</li>
<li class="columnItem">Mary</li><!--will be removed and put under CommonLister-->
</ul>
<ul id="listTwo">
<li class="columnItem">John</li><!--will be removed and put under CommonLister-->
<li class="columnItem">Mark</li>
<li class="columnItem">Mary</li><!--will be removed and put under CommonLister-->
</ul>
<ul id="CommonLister">
<li class="columnItem">John</li>
<li class="columnItem">Mark</li>
</ul>
</div>
$(function() {
$('#run-code').on('click', function(e) {
e.preventDefault();
//What were you doing? nope.
var currentItems = {}; //Blank object
var $mergeColumn = $('#CommonLister'); //Common list reference
$('.columnItem').each(function(i, el) {
var $el = $(el); //Notation I use to differentiate between the regular HTML Element and jQuery element
if (!currentItems.hasOwnProperty($el.html())) {
//Has this name come up before? if not, create it.
currentItems[$el.html()] = []; //Make it equal to a brand spanking new array
}
currentItems[$el.html()].push(el);
//Add the item to the array
});
$.each(currentItems, function(name, data) {
//Loop through each name. We don't actually use the name variable because we don't care what someone's name is
if (data.length > 1) {
//Do we have more than 1 element in our array? time to move some stuff
$.each(data, function(i, el) {
var $el = $(el); //See note above
if (i == 0) {
//If this is the first element, let's just go ahead and move it to the merge column ul
$el.appendTo($mergeColumn);
} else {
$el.remove(); //Otherwise, we've already got this element so delete this one.
} //end if/else
}); //end $.each(data)
} //end if data.length >1
}); //end $.each(currentItems)
}); //end $.on()
}); //end $(
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="run-code" class="btn btn-success">Click Me</button>
<h4>List 1</h4>
<ul id="listOne">
<li class="columnItem">John</li>
<!--will be removed and put under CommonLister-->
<li class="columnItem">James</li>
<li class="columnItem">Mary</li>
<!--will be removed and put under CommonLister-->
</ul>
<h4>List 2</h4>
<ul id="listTwo">
<li class="columnItem">John</li>
<!--will be removed and put under CommonLister-->
<li class="columnItem">Mark</li>
<li class="columnItem">Mary</li>
<!--will be removed and put under CommonLister-->
</ul>
<h4>Common List</h4>
<ul id="CommonLister">
<!--Extra ul will be added here-->
</ul>
It's invalid nesting a ul directly in a ul like this but if you have to, you could use jquery wrapAll:
$( "li" ).wrapAll( "<ul></ul>" );
See fiddle: https://jsfiddle.net/9xLt6d9f/
I agree with charlietfl that it seems strange to do it this way. However, to answer your question, the best way to force this improperly formatted HTML code would be hardcode it into your original file. Try the following code for the end of your file:
<h4>Common List</h4>
<ul id="CommonLister">
<ul id="CommonListerSub">
<!--Extra ul will be added here-->
</ul>
</ul>
Then, simply change one line of your code:
var $mergeColumn = $('#CommonListerSub'); //Common list reference
This will force it to list the list items under the nested ul tags.
I hope this is an acceptable solution. If for some reason it doesn't work, please comment as to what additional limitations you have, and perhaps share the link of the page that is giving you the required template or format specifications.