سؤال

I am trying to perform a fairly simple task: get class name of one element and find and toggle the visibility of another element with an id that matches the class name. Both the class name and id are generated by php and are identical.

HTML

<div class="button">
  <a href="#" class="generatedName"></a>
</div>

<div id="generatedName">
  <p>Content</p>
</div>

jQuery

jQuery('.container').hide();

jQuery('.button a').click(function() {
    jQuery('div#' + this.class).toggle();
});

I have also tried getting the generated class and using a variable in place of this.class:

var button = jQuery('.button a').attr('class');

I have not had any luck. Any assistance would be greatly appreciated. Thanks in advance!

هل كانت مفيدة؟

المحلول

in javascript(dom element), the class property is className, so

jQuery('#' + this.className).toggle();

نصائح أخرى

You need to use .prop() or .attr() to get the class name:

jQuery('#' + $(this).attr('class')).toggle();

However, your code will not work if your element have two or more classes, you should better apply data-* HTML5 attribute:

<div class="button">
    <a href="#" data-target="generatedName"></a>
</div>

then you can use .data() to retrieve data-* attribute:

jQuery('#' + $(this).data('target')).toggle();

Side note: id must be unique, you can simply use # instead of div#

Fiddle Demo

This works:

$('.button a').click(function() {
    var $class = $(this).attr('class');
    $('div#' + $class).toggle();
});

DEMO

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top