Found lots of info on adding class to the thing that’s clicked but not how to apply to another thing. I have a list. Each list item has a unique class. When I click any list item, I’d like to get that class name and apply it to the element AND also remove any class(es) that are on the element. I’d like to do this without JQuery.
Here’s my scaffold, I’m not sure where to startβ¦πππ
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
<li class="typeface-alegreya">
Alegreya
</li>
<li class="typeface-alegreya-sans">
Alegreya Sans
</li>
<li class="typeface-archivo">
Archivo
</li>
<li class="typeface-archivo-narrow">
Archivo Narrow
</li>
</ul>
<main class="typeface-chivo">The density of texture in a written or typeset page is called its color. This has nothing to do with red or green ink; it refers only to the darkness or blackness of the letterforms in mass. Once the demands of legibilty and logical order are satisfied, eveness of color is the typographer's normal aim. And color depends on four things: the design of the type, the spacing between the letters, the spacing between the words, and the spacing between the lines. None is independent of the others.
</main>
<script>
const fontList = document.querySelectorAll('li');
const fontApply = document.querySelector('main');
fontList.addEventListener("click", () => {
// get class of clicked li
// remove class from target (main)
// apply class to target (main)
dialogFonts.close();
});
</script>
</body>
</html>
2
Answers
Firstly,
addEventListener()
is not a method that can be called on theNodeList
returned byquerySelectorAll()
.You could consider using the
forEach()
method to loop through each of the element objects returned fromquerySelectorAll()
, and then call theiraddEventListener()
methods individually.With that out the way, for the main crux of your question. We can clear all classes from the
<main>
element by setting itsclassName
property to an empty string:To copy the class from the
<li>
clicked on, first we should get a reference to the<li>
clicked on in the event listener function. We can get this from theevent
object that is passed to the function:One property on this object is the
target
property which:We can glean the class from the object referenced from
event.target
and apply it tofontApply
(the<main>
element object reference):Full example:
Your question is not very clear on what exactly you want to do.
If you want to get the clicked li you can use the event target and if you want to get the classname use elem.className(). To add a specific class and remove all others you can use elem.setAttribute(‘class’,’classname’).
Hope this help