How to use JavaScript In HTML

We can dynamically manipulate the CSS properties of elements. By selecting the <div> using its ID or class, we can modify its border style, width, and color.

Example: The below code implements JavaScript to dynamically add border to an HTML element.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>JavaScript Border Example</title>
    <link rel="stylesheet" type="text/css" 
        href="style.css">
</head>

<body>
    <div id="myDiv" class="bordered-div">
        <p>
            w3wiki (GFG) is a leading platform for 
            computer science enthusiasts, offering tutorials, 
            articles, and resources on programming, algorithms, 
            data structures, and more.
        </p>
        <p>
            Visit 
            <a href="https://www.w3wiki.org/">
                w3wiki
            </a> 
            for enriching your knowledge and enhancing
            your skills.
        </p>
    </div>

    <script src="script.js"></script>
</body>

</html>
CSS
.bordered-div {
    max-width: 500px;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    margin: 0 auto;
}

p {
    color: #666;
    line-height: 1.6;
    margin-bottom: 20px;
}

a {
    color: #007bff;
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}
Javascript
window.onload = function () {
    const myDiv = document.getElementById('myDiv');
    myDiv.style.border = '6px solid blue';
    myDiv.style.margin = '50px auto';
    myDiv.style.padding = '30px';
    myDiv.style.textAlign = 'center';
};

Output:



How to Set a Border for an HTML Div Tag ?

Borders help us make things look good on websites, this plays an important role in the external view of a website. In HTML and CSS, we have different ways to add borders, making it easier for developers to create attractive web pages that look neat and organized.

Table of Content

  • Inline Styles
  • Internal Styles
  • External Styles
  • Using JavaScript

Similar Reads

Inline Styles

In this approach, we will use the style attribute to add inline styles for the specified element. It’s more convenient for making fast changes, but using it too much can make the code harder to manage and understand....

Internal Styles

When we use internal styles, we put our CSS styles inside the HTML file using the