Getting the whole content of a clicked <li> element - javascript

This is my HTML line:
<li onclick="return open_create_event_screen();">10</li>
I want to get the content of this < li > element (which is '10') through the JavaScript function (open_create_event_screen()) that opens once the < li > element is clicked.
Is it possible to do so?

Old way, where we put inline events into our HTML. The key is to pass this into the function, which is a reference to the element that was acted upon, you could also pass event, and determine the clicked element from the target property (two different approaches).
const open_create_event_screen = (obj) => {
console.log("opening create event screen");
console.log(obj.innerText);
}
<li onclick="open_create_event_screen(this);">10</li>
Here's a more modern approach, where our html is cleaner, and we do the work of assigning the event handlers in javascript.
const open_create_event_screen = (obj) => {
console.log("opening create event screen");
console.log(obj.innerText);
}
const lis = document.querySelectorAll(".eventThing>li");
lis.forEach(li =>
li.addEventListener("click", () => open_create_event_screen(li))
);
<ul class="eventThing">
<li>10</li>
<li>20</li>
</ul>

Related

How to assign dynamic children a click event listener?

I have a parent container with a number of elements, it's not a well defined number of elements, it's generated by using an API once the user starts typing something in an input field. Also these elements are parents to other elements. (I'll give an example below)
The idea is that once the user clicks that element, I want to display an overlay with more information about that specific element. Sounds good, but the things I've tried didn't work so far.
I tried to add an event listener onto the container. Consider this basic HTML template.
<ul>
<li><span>Item 1</span><span>X</span></li>
<li><span>Item 2</span><span>X</span></li>
<li><span>Item 3</span><span>X</span></li>
<li><span>Item 4</span><span>X</span></li>
</ul>
<form>
<input type="text" id="test">
</form>
So here we have an UL which is the parent element and LI are its children. However, LI are also parents to the span tags that are supposedly showing some vital information so I cannot remove those tags.
The input field is here just to add something dyamically, to mimik the way my API works.
So like I said, I have tried to add an event listener on the UL parent >>
const items = ul.querySelectorAll('li');
items.forEach(item => item.addEventListener('click', function(e) {
console.log(this);
}));
});
});
Then I tried to add an event listener to each of the items, but instead of logging one item at a time as I click them, it's logging one, two, three and so forth.
I feel that I'm missing something here and I don't know what it is. Can you guys help me out?
Later edit: I found this solution but it doesn't seem very elegant to me and it's prone to bugs if I change stuff later on (like add more children etc).
ul.addEventListener('click', e => {
const items = ul.querySelectorAll('li');
if(e.target.tagName === 'LI' || e.target.parentElement.tagName === 'LI') {
if(e.target.tagName === 'LI') {
e.target.remove();
} else if(e.target.parentElement.tagName === 'LI') {
e.target.parentElement.remove();
}
}
});
You can use the function Element.closest() to find a parent element.
const ul = document.querySelector('ul');
ul.addEventListener('click', e => {
let li = e.target.closest('LI');
li.remove();
});
document.forms.newitem.addEventListener('submit', e => {
e.preventDefault();
let newitem = document.createElement('LI');
newitem.innerText = e.target.test.value;
ul.appendChild(newitem);
});
<ul>
<li><span>Item 1</span><span>X</span></li>
<li><span>Item 2</span><span>X</span></li>
<li><span>Item 3</span><span><em>X</em></span></li>
<li>Item 4 X</li>
</ul>
<form name="newitem">
<input type="text" name="test">
</form>
The reason that you got all line events every time that you've clicked in a line, is that you are add a event click in ul element and you just need it in the li element
A way very similar that you'd like:
let ul = document.querySelector("ul");
const items = ul.querySelectorAll("li");
items.forEach((item) =>
item.addEventListener("click", function (e) {
let getTargetRow = e.target.parentElement;
if (getTargetRow.nodeName === "LI"){
console.log("the line removed:",getTargetRow.textContent);
getTargetRow.remove();
}
})
);
<ul>
<li><span>Item 1</span><span>X</span></li>
<li><span>Item 2</span><span>X</span></li>
<li><span>Item 3</span><span>X</span></li>
<li><span>Item 4</span><span>X</span></li>
</ul>
<form>
<input type="text" id="test" />
</form>

How can i delete a specific li list on click?

const list = document.getElementById('list')
const addtodo = document.getElementById('addtodo')
//const items = document.querySelector('.item')
const deleteItem = document.querySelector('.delete')
addtodo.addEventListener('keypress', submitTodo)
function submitTodo(event) {
if (event.keyCode == 13) {
event.preventDefault()
let value = addtodo.value
let li = document.createElement('li')
li.innerHTML = `
<img class="unchecked" src="icon/unchecked.svg" />
${value}
<img class="delete" src="icon/icons8-multiply-26.png" /> `
list.appendChild(li)
}
}
deleteItem.addEventListener('click', items)
function items(item) {
if (item.target.classList.contains('delete')) {
item.target.parentElement.remove()
}
}
The code above only allows me to delete one item and its the first one on the list
I try to solve it on my own but couldn't any idea whats wrong
When deleteItem.addEventListener('click', items) is ran, it only attaches the eventListener to the elements currently on the DOM - the ones you create dynamically will not have this eventListener
You can use 'event delegation' instead to listen for clicks, and filter theses clicks based on if the click was coming from the correct element
You can read more about event delegation from davidwalsh's blog and this StackOverflow answer
document.addEventListener('click', function(e) => {
if(e.target && e.target.classList.includes('delete')){
e.target.parentElement.remove()
}
});
You could also make use of the elements onclick attribute, and pass this in the parameter of the function call - this way you can access the HTML Element directly from the parameter; this also avoids having to have an eventListener, or using an if to check if it's the correct class / ID
// Add the function to the onclick attribute of the img
<img class="delete" onclick="deleteItem(this)" src="demo.png" />
// in this function, 'item' refers to the DOM Element that was clicked
function deleteItem (item) {
item.parentElement.remove();
}
This code will allow you to remove the first element on ul .
let list = document.getElementById("list"); // ul element
let remove = document.getElementById("remove"); // remove button
// on double click event
remove.onclick = () => {
// remove the first child from the list
list.removeChild(list.firstChild);
}
<ul id="list">
<li>One</li>
<li>Two</li>
<li>three</li>
</ul>
<input type="button" id="remove" value="Remove First"></input>

Adding event listeners to <li> that are created using javascript

I am quite new to manipulating elements in the DOM in JS so I am creating a simple to do list to get more comfortable and where I can add items using the input and remove items by clicking on the list item.
ALthough this may not be best practice and limitting I am just wanting to use create and remove elements rather than using objects or classes until I get more familar, also using plain/vanilla js so please keep this in mind when answering.
I am trying to add a click event which removes the <li> when the <li> is clicked.
My logic is...
When the page is loaded I can't just run a for loop over all of the <li>s and add event handlers as all of the <li>'s do not exist yet.
So my attempted solution is when the addTaskButton event is triggered, we get all of the <li> that are on the page at the time of the event, we loop through all of them and add an eventlistener to <li>'s that are waiting to be removed when clicked.
This doesn't seem to work and may be overly complicated.
Can someone please explan to me very simply like I'm 5 why this doesn't work or what a better way to do this would be?
Thank you in advance
HTML
<ul id="taskList">
<li>example</li>
</ul>
<input type="text" id="addTaskInput">
<button id="addTaskButton">Add Task</button>
JavaScript
const taskList = document.querySelector("#taskList");
const addTaskInput = document.querySelector("#addTaskInput");
const addTaskButton = document.querySelector("#addTaskButton");
let taskItem = document.querySelectorAll("li");
addTaskButton.addEventListener("click", () => {
let taskItem = document.createElement("li");
taskItem.textContent = addTaskInput.value;
for (let i = 0; i < taskItem.length; i++) {
taskItem[i].addEventListener("click", () => {
let taskItem = document.querySelectorAll("li");
taskList.removeChild(taskItem[i]);
});
}
taskList.appendChild(taskItem);
addTaskInput.value = " ";
});
Here is code i created for your requirement, this implement jQuery $(document).on mechanism in vanilla javascript, now where ever you create an li inside the document, on clicking that li it will be removed.
Explaination
What it does is on clicking the document it checks on which element is clicked (e.target is the clicked element, e is is the click event on document), then checks if the clicked item is an li tag (e.target.tagName will tell us the tag name if the item clicked), so if it is an li just remove it;
const taskList = document.querySelector("#taskList");
const addTaskInput = document.querySelector("#addTaskInput");
const addTaskButton = document.querySelector("#addTaskButton");
addTaskButton.addEventListener("click", () => {
let taskItem = document.createElement("li");
taskItem.textContent = addTaskInput.value;
taskList.appendChild(taskItem);
addTaskInput.value = " ";
});
document.onclick = function(e)
{
if(e.target.tagName == 'LI'){
e.target.remove();
}
}
<ul id="taskList">
<li>example</li>
</ul>
<input type="text" id="addTaskInput">
<button id="addTaskButton">Add Task</button>
Update your for loop like so:
for (let i = 0; i < taskItems.length; i++) {
taskItems[i].addEventListener("click", () =>
taskList.removeChild(taskItems[i]);
});
}
Also your initial taskItem variable should be taskItems and is reflected in the for loop above.
taskList.addEventListener("click", (event) => {
event.target.remove();
});
When the specified event occurs the event object is returned.
The event object has several properties, one of them being target which is the element which is the element which the event occured on. event.target is returned to us and we are applying the remove() method to event.target
because of event "bubbling" or "Event Propagation", we can attach the event handler to an ancestor. It's best to attach the event listener to the closest ancestor element that is always going to be in the DOM (won't be removed).
When an event is triggered-in this case the "click" event. All decending elements will be removed - which in our case as there are only <li>'s this would be fine. But we should be more specific as in a different case we could be attaching this event handler to a div which has several different elements.
To do this we add an if condition to check that the tagName is an <li>
if (event.target.tagName == "LI")
note that the element must be calpitalised
Solution is as follows
taskList.addEventListener("click", (event) => {
if(event.target.tagName == "LI"){
event.target.remove();
}});
Further reading:
Event object and its properties:
https://developer.mozilla.org/en-US/docs/Web/API/Event
Event Bubbling:
https://developer.mozilla.org/en-US/docs/Web/API/Event/bubbles
tagName:
https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName

"If not div" onclick event not including children divs

Using vanilla JS, I'm trying to create an off click - as in, if the body is clicked and it is not a certain element that is clicked, close that element.
However, it works when you click the specified element (it doesn't close), but it fires the event when you click any of that element's child nodes. I'd like the if statement to include any child nodes of that parent element, as well as the parent node itself.
HTML:
<ul id="NavSocial-target" class="Nav_social">
<li class="Nav_social_item">Facebook</li>
<li class="Nav_social_item">Twitter</li>
<li class="Nav_social_item">Google</li>
</ul>
<ul class="Nav_options FlexList">
<li class="Nav_options_item FlexList_item" id="NavSocial-trigger">Social</li>
<li class="Nav_options_item FlexList_item">Curr/Lang</li>
</ul>
Javascript:
this.triggerDOM = document.getElementById('NavSocial-trigger');
this.targetDOM = document.getElementById('NavSocial-target');
// If not list item that triggers model && if not model itself
document.getElementsByTagName('body')[0].onclick = (e) => {
if(e.target !== this.triggerDOM && e.target !== this.targetDOM){
this.removeClass();
}
};
I assume this.triggerDOM is the element you want to ignore. You need to see if the click passed through the element, with a loop:
this.triggerDOM = document.getElementById('NavSocial-trigger');
// ...
document.body.addEventListener("click", e => {
var element = e.target;
while (element && element !== document.body) {
if (element === this.triggerDOM) {
// It was a click in `this.triggerDOM` or one of its
// children; ignore it
return;
}
element = element.parentNode;
}
// It wasn't a click anywhere in `this.triggerDOM`
this.removeClass();
}, false);
Side notes on the above:
document.getElementsByTagName("body")[0] is just a long way to write document.body :-)
Using onclick doesn't play nicely with others; use addEventListener (or attachEvent on IE8 and earlier, if you still need to support seriously obsolete browsers).
Arrow functions accepting a single argument don't need () around the argument list (though of course it's fine to have them there if you prefer the style).
Working example:
this.triggerDOM = document.getElementById('NavSocial-trigger');
// ...
document.body.addEventListener("click", e => {
var element = e.target;
while (element && element !== document.body) {
if (element === this.triggerDOM) {
// It was a click in `this.triggerDOM` or one of its
// children; ignore it
return;
}
element = element.parentNode;
}
// It wasn't a click anywhere in `this.triggerDOM`
this.triggerDOM.parentNode.removeChild(this.triggerDOM);
}, false);
#NavSocial-trigger {
border: 1px solid #ddd;
background-color: #dd0;
}
<!-- Note the really deep nesting -->
<div><div><div><div><div><div><div><div><div><div>
Click
<div>
anywhere
<div>
on
<div>
this
<div>
page
<div>
except
<div id="NavSocial-trigger">
here
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div></div></div></div></div></div></div></div></div>

Event Listener in JavaScript not jQuery

$('ul.mylist').on('click', 'li', function(){})
I want to transform this jQuery line into vanilla but how I can do this ? I looked at jQuery source but I'm confused. Is there simple way to do this in pure Javascript ?
Some features here are browser dependent, but this is basically how it goes...
// select all UL elements with the `mylist` class
var uls = document.querySelectorAll('ul.mylist');
// Iterate the collection, and bind the `click` handler
for (var i = 0; i < uls.length; i++)
uls[i].addEventListener('click', handler, false);
// The `click` handler iterates starting with `event.target` through its
// ancestors until the bound element is found. Each element matching the
// "LI" nodeName will run your code.
function handler(event) {
var node = event.target;
do {
if (node.nodeName === "LI") {
// RUN YOUR CODE HERE
}
} while (node !== this && (node = node.parentNode));
}
You can make the selector test more broad by using node.matchesSelector(".my.selector"), though that method is implemented using browser-specific property flags in some browsers, so you'd need to first expose it on the Element.prototype under the proper name.
You can bind click listener to any element as follows:
<ul id="mylist">
<li> item 1</li>
<li> item 2</li>
<li> item 3</li>
<li> item 4</li>
</ul>
<script type="text/javascript">
function click_handler(){
alert('you clicked a list');
}
var list=document.getElementById("mylist");
list.onclick=click_handler;
</script>
here is JSFiddle

Categories