How to give CSS class in jQuery?

Duomly - Aug 5 '20 - - Dev Community

This post was originally published at https://www.blog.duomly.com/6-most-popular-front-end-interview-questions-and-answers-for-beginners-part-3/#how-to-give-css-class-in-jquery


Did you think jQuery is dead already, and nobody uses it?

Nothing more wrong!

It’s kinda similar, like with PHP, that modern web-development doesn’t want to use it so much, but still, most of the internet is powered by that tech.

The jQuery library is still alive, and around 75% of all websites are using jQuery, so it is definitely worth knowing at least basics.

One of the features that we’ll be using with jQuery is to manipulate the elements, add styles, hide, show, add or remove attributes.

In this case, I’ll show you the two things, the first one (you’ll use it very often) is how to take element by the selector.

When we take element by a selector (in this case, we take it by id), we can add the class to the selected element.

Let’s take a look at the code example that I’ve created.

In the code example, I’ve created an element with id “hero”.

Next, I’ve created the js script, where I’ve used jQuery to take the “hero” element by its id.

And as the last step, I’ve added the class “rounded” to that element.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Learn coding on Duomly.com</title>
    <script
    src="https://code.jquery.com/jquery-3.5.1.min.js"
    integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
    crossorigin="anonymous"></script>
  </head>
  <body>
    <div id="hero">
      This is hero element
    </div>
    <script>
      $("#hero").addClass('rounded');
    </script>
  </body>

Duomly - Programming Online Courses

Thank you for reading,
Radek from Duomly

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player