How to use the attr() method In JQuery

The attr() method will also be used to set the style attribute with the passed value.

Syntax:

$('element_selector').attr('attribute', 'value'); 

Example: The below example will illustrate the use of the attr() method to add the style=”display: block” to an element using jQuery.

html




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="utf-8">
    <title>
        How to add `style=display:“block”`to
        an element using jQuery?
    </title>
    <style>
        p {
            color: green;
            font-weight: bold;
            cursor: pointer;
        }
    </style>
    <script src=
"https://code.jquery.com/jquery-1.10.2.js">
    </script>
</head>
 
<body style="text-align:center;">
    <h1 style="color:green;">
        w3wiki
    </h1>
    <h2> How to add `style=display:“block”`to
        an element using jQuery? </h2>
    <div>
        <p style="display: none">
            It is displayed using the
            style="display: block"
            property added using css() method.
        </p>
        <button>click to display</button>
    </div>
    <script>
        $('button').click(()=>{
            $("p").attr('style', 'display: block');
        });
    </script>
 
</body>
 
</html>


Output:

How to add `style=display:“block”` to an element using jQuery?

In this article, we will learn how we can add the style=display: “block” inline style to the HTML elements using jQuery. There are multiple approaches to achieve this task as follows:

Table of Content

  • Using the CSS() method
  • Using the show() method
  • Using the attr() method
  • Using the prop() method

Similar Reads

Using the CSS() method

The css() method of jQuery is used to add the inline styles to the selected element by passing the CSS property and its value as parameters to it....

Using the show() method

...

Using the attr() method

The show() method can also be used to set the style=”display: block” property to an element....

Using the prop() method

...

Contact Us