简体   繁体   中英

How do you first find a class that contains a string and then get the id of the element with that class you just found? Using Javascript

What I'm trying to do is search a page for an element that has the string 'tab_selected' in the class name. The class name is more than just 'tab_selected'. Its 'tab_selected + the UUID'. The UUID changes so all I really want to search for is if the class name contains 'tab_selected' and then if it does I want to get the ID of that element and set the cookie with that ID. I'm a terrible Noob with javascript so any direction would be awesome. Thanks!

EDIT:

Thats actually fairly simple with jQ:

var sel = '.tab_selected_left_horizontal, .tab_selected_right_horizontal, .tab_selected_text_horizontal, .tab_selected_left_vertical, .tab_selected_text_vertical, .tab_selected_right_vertical';

var ids = $(sel).map(function(){
  return $(this).attr('id');
});

I would recommend adding an additional class of tab_selected without the UUID. This way you can grab all the elements of that class without having to parse class names. So you element might look like this:

<div class="tab_selected tab_selected-UUID"></div>

This way you can just do $('.tab_selected') .

Just a guess, but if you're trying to save a cookie from your selected tab jquery can do it for your:

You will need, jquery-ui and a cookie plugin for it, then all you have to do is change your tabs initialization:

<script type="text/javascript">
  $(function() {
    $("#tabs").tabs({
      cookie: {
        // store cookie for a day, without, it would be a session cookie
        expires: 1
      }
    });
  });
</script>

Cookie plugin is here

Ok it was much more simple than I was making it. Thanks everyone for your help! Here was my test and it worked perfectly.

$(document).ready(function() {
$(".tab_selected_text_horizontal").attr("id");
var title = $(".tab_selected_text_horizontal").attr("id");
alert(title);
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM