Button that when clicked shows only the content of a certain class

4

Hello, I'm creating a Javascript system, where I need a button to show only the paragraphs with a given class in a div with hidden content.

Example:

 <button id="btn1">Abre classe1</button>
 <div id="conteudo">
     <p class="classe1">Teste1</p>
     <p class="classe1">Teste2</p>
     <p class="classe2">Teste3</p>
 </div>

I would like that when this button is clicked, the div loads only the text Test1 and Test2. Is it possible?

Thank you.

    
asked by anonymous 24.07.2014 / 23:14

2 answers

3

To show these elements with the class you want you can use like this: link

$('#btn1').on('click', function(){
    $('#conteudo p.classe1').show();
});

I'm assuming you have a CSS like this:

#conteudo p {
    display: none;
}

However it would be useful to add more information to this button to create more general and not so localized code, in case there are buttons that show other classes.

For example, you could add a data-classe field where you would add the exact name of the class that this button should show.

Like this: link

HTML

<button id="btn1" data-classe="classe1">Abre classe1</button>
<button id="btn2" data-classe="classe2">Abre classe2</button>
<div id="conteudo">
    <p class="classe1">Teste1</p>
    <p class="classe1">Teste2</p>
    <p class="classe2">Teste3</p>
</div>

JavaScript / jQuery

$('button').on('click', function () {
    var classe = $(this).data('classe');
    $('#conteudo p.' + classe).show();
});

And in this case javascript does not have to change anymore, regardless of having 20 different classes.

    
24.07.2014 / 23:28
2

If all content is hidden and is displayed only at the click of the button, you can do

Demo: JSFiddle

Example:

CSS

/*oculta todos os parágrafos dentro da div conteúdo*/
#conteudo p {display:none;} 

jQuery

//Ao clicar no botão com id #btn1, exibe os parágrafos com .classe1
$('#btn1').click(function(){
    $('p.classe1').show('slow');
});
    
24.07.2014 / 23:23