How can I get a part of the value of class attribute?

Viewed 34

Here is my HTML structure:

<tr>
    <td class="option_name_twitter">Something</td>
    <td class="option_loading">
        <img src="img/checked_successfully.png">
    </td>                        
</tr>
<tr>
    <td class="option_name_instagram">Something else</td>
    <td class="option_loading">
        <img src="img/checked_successfully.png">
    </td>                        
</tr>

And here is my code:

$(document).on('click', "img[src$='checked_successfully.png']", function () {
    var name = $(this).closest('td.option_loading').sibilings('td.^option_name_').attr('class');
})

I'm trying to get the last part of the classname's value of an element that starts with option_name_. So the expected result is either twitter or instagram. How can I do that?

1 Answers

You can achieve this by getting the class from the sibling td, splitting it in to an array using _, then pop() off the last element to get the value you need. Something like this:

$(document).on('click', "img[src$='checked_successfully.png']", function() {
  var name = $(this).closest('td.option_loading').prev('td').attr('class');
  var site = name.split('_').pop();
  console.log(site);
})
img {
  border: 1px solid red;
  width: 30px;
  height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="option_name_twitter">Something</td>
    <td class="option_loading">
      <img src="img/checked_successfully.png">
    </td>
  </tr>
  <tr>
    <td class="option_name_instagram">Something else</td>
    <td class="option_loading">
      <img src="img/checked_successfully.png">
    </td>
  </tr>
</table>

You should however note that using the class string in this way is not ideal, as it's very easily broken. Adding another class at the end of the attribute will break this code. A much better approach would be to store the value you need in its own data attribute - assuming you have access to edit the HTML.

Related