How to change css class of html paragraph with javascript?

Member

by lottie , in category: Javascript , 9 months ago

How to change css class of html paragraph with javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 9 months ago

@lottie 

To change the CSS class of an HTML paragraph using JavaScript, you can do the following:

  1. Give your paragraph an id or class attribute in the HTML code. For example, let's give it an id of "myParagraph":
1
<p id="myParagraph">This is a paragraph.</p>


  1. In your JavaScript code, use the getElementById method to select the paragraph element:
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. Use the classList property to add, remove, or toggle a CSS class on the paragraph element. For example, you can use the add method to add a class:
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.