JS DOM HTML/CSS Manipulation

HTML
CSS
C#
SQL

DOM HTML/CSS Manipulation:

JavaScript empowers developers to dynamically manipulate the Document Object Model (DOM) and control the styling of HTML and CSS elements. Here’s a breakdown of how you can select, manipulate, and style elements in the DOM using JavaScript:

1. Selecting Elements:

– Use `document.querySelector()` to select the first element that matches a CSS selector.
– Use `document.querySelectorAll()` to select all elements that match a CSS selector.

Example:

   const element = document.querySelector(‘.my-class’);

2. Manipulating Element Properties:

– Access and modify the properties of a selected element using JavaScript.
– For example, change the text content of an element using the `textContent` property.

Example:

   element.textContent = ‘New text content’;

3. Adding/Removing Classes:

– Utilize the `classList` property to add or remove classes from an element.
– Use the `add()` method to add a class and the `remove()` method to remove it.

Example:

element.classList.add(‘new-class’);
element.classList.remove(‘old-class’);

4. Styling Elements:

– Directly manipulate the inline styles of an element using the `style` property.
– Set specific style properties like `color`, `fontSize`, etc.

Example:

   element.style.color = ‘red’;
   element.style.fontSize = ’20px’;

5. Creating and Adding New Elements:

– Generate new HTML elements dynamically using JavaScript.
– Use methods like `createElement()` to create an element and `appendChild()` to add it to the DOM.

Example:

const newElement = document.createElement(‘div’);
   newElement.textContent = ‘I am a new element’;
   document.body.appendChild(newElement);

These manipulation techniques provide the flexibility to create interactive and dynamic web pages by modifying the content and style of elements based on user interactions or other events.

Method / Property

Description

Example

style.property

Sets or gets the value of a specific CSS property for an element              

const element = document.querySelector(‘.my-element’);<br>element.style.backgroundColor = ‘red’;

className

Sets or gets the class name of an element

const element = document.querySelector(‘.my-element’);<br>element.className = ‘new-class’;

classList.add(className)

Adds a new class to the class list of an element

const element = document.querySelector(‘.my-element’);<br>element.classList.add(‘new-class’);

removeAttribute(name)

Removes an attribute from an element

const element = document.querySelector(‘.my-element’);<br>element.removeAttribute(‘data-id’); 

setAttribute(name, value)

Sets the value of an attribute for an element

const element = document.querySelector(‘.my-element’);<br>element.setAttribute(‘data-id’, ‘123’);

getAttribute(name)

Gets the value of an attribute for an element

const element = document.querySelector(‘.my-element’);<br>const id = element.getAttribute(‘data-id’);

 

element.offsetHeight

Returns the height of an element, including padding and border

var element = document.getElementById(“myElement”); console.log(element.offsetHeight);

element.offsetWidth

Returns the width of an element, including padding and border

var element = document.getElementById(“myElement”); console.log(element.offsetWidth);

element.style.display

Gets or sets the display property of an element

document.getElementById(“myElement”).style.display = “none”;

element.style.visibility

Gets or sets the visibility property of an element                             

document.getElementById(“myElement”).style.visibility = “hidden”;

element.style.opacity

Gets or sets the opacity property of an element              

document.getElementById(“myElement”).style.opacity = “0.5”;

element.style.backgroundColor

Gets or sets the background-color property of an element              

document.getElementById(“myElement”).style.backgroundColor = “red”;

 

element.style.color

Gets or sets the color property of an element

document.getElementById(“myElement”).style.color = “blue”;

element.style.fontFamily

Gets or sets the font-family property of an element              

document.getElementById(“myElement”).style.fontFamily = “Arial”;

element.style.fontSize

Gets or sets the font-size property of an element

document.getElementById(“myElement”).style.fontSize = “20px”;

element.style.fontWeight

Gets or sets the font-weight property of an element              

document.getElementById(“myElement”).style.fontWeight = “bold”;

element.style.textAlign

Gets or sets the text-align property of an element                             

document.getElementById(“myElement”).style.textAlign = “center”;

element.style.padding

Gets or sets the padding property of an element              

document.getElementById(“myElement”).style.padding = “10px”;

 

element.style.margin

Gets or sets the margin property of an element

document.getElementById(“myElement”).style.margin = “10px”;

element.style.border

Gets or sets the border property of an element

document.getElementById(“myElement”).style.border = “1px solid black”;

Naming Convention in CSS Properties in JavaScript

CSS properties in JavaScript are typically written in camel case. Camel case is a naming convention where multiple words are joined together, and each word, except the first, starts with a capital letter. This convention is widely used for JavaScript variables and functions.

Here are examples of CSS properties in JavaScript using camel case:

  // Camel Case
  element.style.backgroundColor = ‘red’;
  element.style.fontSize = ’16px’;
  element.style.marginTop = ’10px’;

In contrast, the kebab case is another common convention where multiple words are separated by hyphens. While kebab case is often used in CSS for class names and IDs, it’s less common in JavaScript for accessing style properties directly:

// Kebab Case (less common in JavaScript)
  element.style[‘background-color’] = ‘red’;
  element.style[‘font-size’] = ’16px’;
  element.style[‘margin-top’] = ’10px’;

Pascal case, where each word starts with a capital letter, is less common for CSS properties in JavaScript but might be used in certain cases:

// Pascal Case (less common in JavaScript)
  element.style.BackgroundColor = ‘red’;
  element.style.FontSize = ’16px’;
  element.style.MarginTop = ’10px’;

It’s important to note that camel case is the more prevalent and recommended convention when working with CSS properties in JavaScript. It aligns well with JavaScript’s typical naming conventions and is more readable.

Course Video

Examples for Practice

You have to solve all the questions given below in the editor without copy-pasting.

1. Create a Web Page in which we have to add a “div” Element of class “myDiv” and insert Text inside this Div Element.
Note:- Do it using DOM Elements.

The task is to create a web page where you use JavaScript and the Document Object Model (DOM) to add a <div> element with the class “myDiv” and insert text inside this <div>.
Use DOM to Create and Modify Elements:
– Inside the JavaScript code, use the DOM to create a new <div> element.
– Set the class attribute of the <div> to “myDiv”.
– Insert text content inside the <div>.

Here’s an example program:

// Create a new div element
var myDiv = document.createElement(“div”);

// Set the class attribute of the div to “myDiv”
myDiv.className = “myDiv”;

// Insert text content inside the div
myDiv.textContent = “Hello, I am inside myDiv!”;

// Append the div to the body of the HTML document
document.body.appendChild(myDiv);

Output

2. Create a Web Page in which we have to add an Element of class “myDiv” and insert Text inside this Element but take the Element name and Text node from User and also pass the Element name and Text node as a parameter to a Function.
Note:- Do it using DOM Elements

The task is to create a web page where you use JavaScript and the Document Object Model (DOM) to add an element with a specified class and insert text inside it. The element name and text content should be taken from the user, and a function should be used to achieve this.
Use DOM and Function:
– Inside the JavaScript code, create a function that takes parameters for the element name and text content.
– Use the DOM to create the specified element, set its class, and insert text content.
– Call the function with values taken from the user.

Here’s an example program:

// Function to create an element with class and text content
function createAndInsertElement(elementName, textContent) {
// Create a new element based on user input
var newElement = document.createElement(elementName);

// Set the class attribute of the element to “myDiv”
newElement.className = “myDiv”;

// Insert text content inside the element
newElement.textContent = textContent;

// Append the element to the body of the HTML document
document.body.appendChild(newElement);
}

// Get user input for element name and text content
var userElementName = prompt(“Enter the element name (e.g., div, p, h2):”);
var userTextContent = prompt(“Enter the text content:”);

// Call the function with user input as parameters
createAndInsertElement(userElementName, userTextContent);

Output

3. Create a Web Page in which we have to add a “div” Element of class “myDiv” Insert text inside this Div Element and change the style of the div using DOM Element.

The task is to create a web page where you use JavaScript and the Document Object Model (DOM) to add a <div> element with the class “myDiv,” insert text inside it, and change the style of the <div>.
Use DOM to Create and Modify Elements:

– Inside the JavaScript code, create a new <div> element.
– Set the class attribute of the <div> to “myDiv.”
– Insert text content inside the <div>.
– Change the style of the <div> using the DOM.

Here’s an example program:

// Create a new div element
var myDiv = document.createElement(“div”);

// Set the class attribute of the div to “myDiv”
myDiv.className = “myDiv”;

// Insert text content inside the div
myDiv.textContent = “Hello, I am inside myDiv!”;

// Change the style of the div
myDiv.style.backgroundColor = “lightblue”;
myDiv.style.padding = “20px”;
myDiv.style.border = “2px solid navy”;
myDiv.style.color = “white”;

// Append the div to the body of the HTML document
document.body.appendChild(myDiv);

Output

4. Create a Web Page with two unordered list items and add the third one before the second item using Dom Element.
Before:-    Coffee           After:- Coffee
                 Tea                           Drink
                                                  Tea

The task is to create a web page with two unordered list items and then add a third item before the second one using JavaScript and the Document Object Model (DOM).
Use DOM to Create and Modify Elements: 

– Create a new <li> element and store it in the variable.
– Set the text content of the new list item to “Drink.”
– Get the reference to the existing second list item using its index within the <ul> with the ID “myList.”
– Insert the new list item before the second list item by using the insertBefore method. 

Here’s an example program:

<body>

<ul id=”myList”>
<li>Coffee</li>
<li>Tea</li>
</ul>

<script>
// Create a new list item for “Drink”
var newListItem = document.createElement(“li”);
newListItem.textContent = “Drink”;

// Get the reference to the existing second list item
var secondListItem = document.getElementById(“myList”).getElementsByTagName(“li”)[1];

// Insert the new list item before the second list item
secondListItem.parentNode.insertBefore(newListItem, secondListItem);
</script>

</body>

Output