0

I am making the simple site but stuck on the very simple concept that is to take the values from class attribute value from button having multiple classes.When I am trying to use attr(), It shows string having multiple classes.My problem is how to access it???, The code of this is given below.

HTML CODE

<button id="view" class="cc btn btn-primary">View</button>

JS CODE

<script type="text/javascript">
$('button').click(
function()
{
$id=$(this).attr('id');
$class=$(this).attr('class');////////cc btn btn-primary but i want only `cc`
}
)
</script>
2

2 Answers 2

0

You almost there.

This $(this).attr('class') returns a string with the whole set of class names.

An alternative is splitting the class names using this regex /\s+/ and get the desired class name.

Use this regex /\s+/ to split the classnames with these formats: cc btn btn-primary, or cc btn btn-primary, or cc btn btn-primary, Etc,.

$('button').click(
  function() {
    //$id = $(this).attr('id');
    var classNames = $(this).attr('class').split(/\s+/);
    console.log(classNames)
    console.log(classNames.length ? classNames[0] : '');

    //Check is classname 'cc' exists.
    console.log(this.classList.contains('cc')); // Native attribute classList.        
    console.log($(this).hasClass('cc')); // jQuery function hasClass.
  }
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="view" class="cc      btn      btn-primary">Click this View</button>

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

Comments

0

@nancy harigton, method I usually go with is to split the classes into an array, like so: https://jsfiddle.net/90dty5oo/8/

$('button').click(function() {
    var myClass= $(this).attr('class');

    myFirstClass = myClass.split(" ");

    alert(myFirstClass[0]);
});

You also do not need the first line inside the function regarding the ID.


ES6 Update

Here's the ES6 version of the code using arrow functions and template literals:

document.querySelectorAll('button').forEach(button => {
  button.addEventListener('click', () => {
    const myClass = button.getAttribute('class');
    const [myFirstClass] = myClass.split(' ');
    alert(myFirstClass);
  });
});

4 Comments

@allenski, ya It is working but the problem is how to access it? Is it an array? It is showing a string.....
@nancy, do you just need one of the classes? or all of them
I want only cc class string for attr comparison
Split into an array. I have updated my answer for you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.