0

I have two buttons with different ids. I want to hide specific paragraph when button with similar id is clicked.

Here's my code

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var id = $(this).attr("id").replace('test', '');
        $('.p #'+id+'').hide();
    });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<div class="gallery">
<div class="picture">
<p id="1">This is a paragraph.</p>
<p id="2">This is another paragraph.</p>
</div>
</div>


<button id=test1>Click me1</button>
<button id=test2>Click me2</button>

</body>
</html>

As you can see if i click button with id "test1" I want to hide the paragraph with id "1". But It's not working.

1 Answers1

0

Just get rid of the .p in your selector:

$('#'+id+'').hide();

You don't have any elements with a class value of p. But, more to the point, you don't need to use any other selector elements because you're targeting an id which is already unique.

Note: Please also refer to information about restrictions on id values. In particular, id should not begin with a number character. (Unless that changes in newer HTML versions?) While your code, with my above modification, does seem to work as intended in my browser. It may not be guaranteed to work in any given browser.

Instead, however, you can use a letter in your id values and achieve the same result. For example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var id = $(this).attr("id").replace('test', '');
        $('#'+id+'').hide();
    });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<div class="gallery">
<div class="picture">
<p id="A">This is a paragraph.</p>
<p id="B">This is another paragraph.</p>
</div>
</div>


<button id="testA">Click me1</button>
<button id="testB">Click me2</button>

</body>
</html>
David
  • 208,112
  • 36
  • 198
  • 279
  • 1
    ID’s Cannot Start With a Number – Pedram Nov 18 '17 at 11:24
  • 1
    @pedram: Hmm, good point. Though this code appears to be working, it's not necessarily *guaranteed* to work in any given browser. I'll include that in the answer. – David Nov 18 '17 at 11:26