/    Sign up×
Community /Pin to ProfileBookmark

How do I add a class to a given element

“`
<div class=”Quiztext”>
<ul>
<li class=”ListItem” data-pos=”0″>Correct Answer</li>
<li class=”ListItem” data-pos=”1″>Wrong Answer</li>
<li class=”ListItem” data-pos=”2″>Wrong Answer</li>
<li class=”ListItem” data-pos=”3″>Wrong Answer</li>
</ul>
</div>

“`

Now I want to create a JavaScript function that will add a class to the existing class, whan click on it. (not replace, but add).

“`
<li class=”ListItem a0″ data-pos=”0″>Correct Answer</li>
<li class=”ListItem a1″ data-pos=”1″>Wrong Answer</li>
<li class=”ListItem a3″ data-pos=”2″>Wrong Answer</li>
<li class=”ListItem a4″ data-pos=”3″>Wrong Answer</li>

“`

Please Give The Answer How To, How can I do that?

to post a comment
CSSHTMLJavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumJan 31.2021 — Yes, adding a class can be done by using the classList property:

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
Copy linkTweet thisAlerts:
@AmardonJan 31.2021 — <div id="mydiv"></div>

const div = document.getElementById('mydiv');

div.setAttribute('class','class-name')

console.log(div)//<div id="mydiv" class="class-name"></div>


Copy linkTweet thisAlerts:
@SempervivumJan 31.2021 — @Amardon#1627454

`div.setAttribute('class','class-name')`

I do not recommend to do it this way as it will overwrite all classes set previously! The TO wrote:
>not replace, but add
×

Success!

Help @mrumang spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...