I want to show an alert when I click on "aaa" or "bbb" .How can I access li elements without the class "click" from the ul with the id = parent ? For the other elements I used :
var elements = document.getElementById('parent');
var classElem = document.getElementsByClassName('click');
I thought of something like : liW = elements - classElem
but this doesn't work.
This is the html I used :
<html>
<head>
</head>
<body> <ul id = "parent">
<li> aaa </li>
<li> bbb </li>
<li class ="click"> ccc </li>
<li class ="click"> ddd </li>
</ul>
<ul> <li> eee </li>
</ul>
</body>
You can use Array.filter
, like so:
var liW = [].filter.call(
document.getElementById('parent').children, // the LI elements
function(li) {return !li.classList.contains('click');}
);
This will give you an array of nodes corresponding to the <li>
tags that do not have class="click"
.
You can do this by looping through all the child li
elements, checking if each of them has the class click
, and if not, make the alert show up when clicked.
var elements = document.getElementById('parent').getElementsByTagName('li');
function elementClicked(elem) {
alert('test');
}
for(var i = 0; i < elements.length; i++) {
if(!elements[i].classList.contains('click')) {
elementClicked(elements[i]);
}
}
You can put the event listener on the parent element - the UL - and check if the target element has the class.
example -
list = document.getElementById('parent');
list.addEventListener('click',function(e){
if (e.target.className.indexOf('click') === -1) alert(test);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.