@lottie
To change the CSS class of an HTML paragraph using JavaScript, you can do the following:
1
|
<p id="myParagraph">This is a paragraph.</p> |
1
|
var paragraph = document.getElementById("myParagraph"); |
If you gave your paragraph a class name instead of an id, you can use the getElementsByClassName
method:
1
|
var paragraphs = document.getElementsByClassName("myParagraph"); |
Keep in mind that getElementsByClassName
returns a collection of elements, so if you want to change the class of a specific paragraph, you may need to further specify the index, like so:
1
|
var paragraph = paragraphs[0]; // Change 0 to the desired index |
1
|
paragraph.classList.add("newClass"); |
You can use the remove
method to remove a class:
1
|
paragraph.classList.remove("oldClass"); |
And you can use the toggle
method to toggle a class on and off:
1
|
paragraph.classList.toggle("active"); |
That's it! By using these steps, you can dynamically change the CSS class of an HTML paragraph element with JavaScript.