privateer35 privateer35 - 1 year ago 48
Javascript Question

Store the n class declaration from an HTML tag in Javascript

I have dynamically generated

div
that receives two generated classes applied to it. For example, I have :

<div class="container">...</div>


Then after I mess with it using some Javascript, it becomes:

<div class="container post post-hello-world">...</div>


For this example how can I grab the third class (
post-hello-world
) and store it somewhere to be used for something else in my Javascript code using pure Javascript?

Answer Source

Use classList and item if the class you want is always third:

var className = document.getElementsByClassName('container')[0].classList.item(2);

See

Demo

Try before buy