Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the ID of a Class in JavaScript

I want to get the ID of an element that I found by using getElementsByClassName()
Here is what my code looks like:

let className = document.getElementsByClassName('some-class')
for (let i = 0; i < className.length; i++) {
    if (className.GETID.toLowerCase().includes('some text')) {
        //  do something
    }
}

So basically what I want is to replace GETID with some kind of method or anyway to get the id of the Element that I have found by using the getElementsByClassName() method.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

See Element.id. Note that this is not a method as your question asks for, but a property instead. This is how you’d use it with your code:

let className = document.getElementsByClassName('some-class')
for (let i = 0; i < className.length; i++) {
    if (className[i].id.toLowerCase().includes('some text')) {
        //  do something
    }
}

The .id property is set for every DOM element regardless of whether it was retrieved with getElementById().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading