1

I'm trying to get class name of the component in html. I have code like this:

<div class="dropdown-content"><a class="label" onclick="getComponentId(this)" href="#">Open terminal</p></div>

And this is my code snippet:

function getComponentId(el) {
  var componentId = el.id;
  var className = document.getElementsByClassName(el)
  alert(className)
  concatenateCredentials(credentials,componentId)
}
<div class="dropdown-content"><a class="label" onclick="getComponentId(this)" href="#">Open terminal</p></div>

I want to fetch class name "label". Above solution didn't work.

3
  • 1
    el.className should be sufficient Commented Jul 26, 2019 at 7:14
  • Unfortunately not. This solution don't give me any output alert. Commented Jul 26, 2019 at 7:16
  • 1
    You are retrieving the a node list of elements with that class name, not the class name itself. Commented Jul 26, 2019 at 7:29

3 Answers 3

4

You can simply look at the className property on the element:

function getComponentId(el) {
  console.log('className: ' + el.className);
}
<a class="label" onclick="getComponentId(this)" href="#">Open terminal</a>

Sign up to request clarification or add additional context in comments.

Comments

0

document.getElementByClassName returns an element from the class name.

You should be looking for el.className or document.getElementById(el.id).classList

2 Comments

I assume you meant getElementsByClassName? It's plural.
Yes, that's a typo.
0

Here's my solution

function getComponentId(x) {
  var y = x.className;
  alert(y);
}
<div class="dropdown-content">
  <a class="label" onclick="getComponentId(this)" href="#">Open terminal</a>
</div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.