jason
jason

Reputation: 2259

How do I parse class names of an html element?

I am using class names on my <a> elements so that I categorize them for our analytics(e.g. "form", "favorite", "carousel link", etc). The class name used does not have any css styling associated with it; the purpose is strictly to aid the analytics in categorizing the link. This is done by having some js that runs when the page loads and attaches an onclick function to all links. This function gets the text of the link and the link's class. An ajax http get is sent to our internal Analtyics application with the text of the link clicked and the name of the link class (as the category).

My questions regarding this are:

1) Since a given <a> (or any html element for that matter) can have one or more classes, is there a way to know where one class name ends and another begins? In my experience, I've seen the class names separated by only spaces so is parsing this even possible if one of the classes is a multi-word value separated by spaces?

2) I have a feeling this could be handled in a better manner. Any thoughts on this?

Upvotes: 1

Views: 626

Answers (2)

Jamiec
Jamiec

Reputation: 136074

To expand on the answer by @SimonMason, who pointed out that using a data-* attribute gives you much clearer control over what to do with your analytics links. I notice you tagged this jQuery, which makes this easier still

See the snippet below

$(document).on('click','[data-analytics]',function(){
   var analytics = $(this).data('analytics');
  alert('You clicked a link tagged: ' + analytics);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-analytics="form" href="#">A form link</a> <br>
<a data-analytics="form" href="#">Another form link</a>  <br>
<a data-analytics="carousel" href="#">A carousel link</a> <br>

Upvotes: 1

Simon Mason
Simon Mason

Reputation: 561

I'd go with a custom data tag for this:

data-analytics="form"

etc

That way you can be sure it is not going to conflict with any of your css / js hooks as you have effectively created a unique name space for your analytics references.

Upvotes: 3

Related Questions