Skip to content

Commit 36c9cbe

Browse files
committed
Styling DOM Elements
1 parent f6c79d0 commit 36c9cbe

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Courses/IBM-JavaScript-Essentials/README.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1797,3 +1797,63 @@ Finding elements within a container involves searching for and accessing HTML el
17971797
</body>
17981798
</html>
17991799
```
1800+
1801+
- Styling DOM Elements:
1802+
1803+
1. style property - You can directly access and modify the inline styles of an HTML element using the style property. This method is beneficial for dynamically adjusting the appearance of elements based on user interactions or events.
1804+
1805+
```html
1806+
<html>
1807+
<body>
1808+
<button id="myBtn" onclick="updateStyle()">Click Me</button>
1809+
<button id="myBtn1">Click Me 2</button>
1810+
<script>
1811+
const button = document.getElementById("myBtn1");
1812+
const button1 = document.getElementById("myBtn1");
1813+
1814+
function updateStyle() {
1815+
button.style.backgroundColor = "blue";
1816+
button.style.color = "white";
1817+
button.style.fontSize = "16px";
1818+
}
1819+
</script>
1820+
</body>
1821+
</html>
1822+
```
1823+
1824+
2. classList property - The class list property facilitates adding, removing, or toggling CSS classes on an element. This property is especially useful for applying predefined styles from CSS classes and enables the toggling of classes in response to user interactions.
1825+
1826+
```
1827+
element.classList.add(className)
1828+
element.classList.remove(className)
1829+
element.classList.toggle(className)
1830+
element.classList.contains(className)
1831+
```
1832+
1833+
3. setAttribute - The setAttribute method allows you to set or modify the style attribute of an element using a string containing inline CSS.While effective, the set attribute process replaces the entire style attribute of an element.
1834+
1835+
```html
1836+
<html>
1837+
<body>
1838+
<p id="myText" style="color: red">This is a red text</p>
1839+
<script>
1840+
const text = document.getElementById("myText");
1841+
text.setAttribute("style", "color: blue; font-size: 20px;");
1842+
</script>
1843+
</body>
1844+
</html>
1845+
```
1846+
1847+
4. remove property - the remove property method is useful for selectively removing specific CSS properties from an element's inline style, this method provides a way to reset or adjust styling on a granular level.
1848+
1849+
```html
1850+
<html>
1851+
<body>
1852+
<p id="myText" style="color: red; font-size: 30px;">This is a red text</p>
1853+
<script>
1854+
const text = document.getElementById("myText");
1855+
text.style.removeProperty("font-size");
1856+
</script>
1857+
</body>
1858+
</html>
1859+
```

0 commit comments

Comments
 (0)