1 Star2 Stars3 Stars4 Stars5 Stars (7 votes, average: 5.00 out of 5)

JavaScript Get Element By Class Name

In order to use JavaScript Get element by class name you have to have a class. You can use a class in a div or any tag that you want. Here are a few examples of class names and how they are used.

<div class="anyName"></div>
<p class="anyName">Paragraph Text</p>
<span class="anyName">This is a span</span>
<h1 class="anyName">This is a heading</h1>

You Can Use A Class Anywhere

You can use a class anywhere in HTML. Name the class anything that you want. The name of the class does not matter. However when you are targeting the class in JavaScript it does matter that you use the name you give it.

Tip: Click on images to make them larger. If you find anything wrong on this page or need further assistance please comment below or contact me. 🙂

Targeting A Class In JavaScript

Lets say that we named our class myclass. It should look something like this.

<span class="myclass"></span>

To target “myclass” in JavaScript the syntax will look like this.

Subscribe To My YouTube Channel:
<script>document.getElementsByClassName('myclass');</script>

If you want to put HTML in the JavaScript you would do something like this.

<script>document.getElementsByClassName('myclass').innerHTML='<p>This is some text.</p>']

JavaScript Get Elements by Class Name is Different Than JavaScript Get Element by id

The important thing to note is that targeting a class name is different than targeting an id. In JavaScript id’s and classes are totally different. The syntax use is different too. A class is targeted plurally and an id is targeted singularly.

JavaScript Get Element By Class Name was last modified: December 30th, 2015 by Maximus Mccullough

Please like, share and subscribe.

Advanced Programming Made Easy

I hope you enjoyed the article. If I was able to help you please consider a tip for the content.

One Time Tip

more tips

Reoccuring Tips

Tips

Cool People Share:
javascript-get-elements-by-class-name

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.