1

I want to change my <p> tag style.

My html code:

<input type="checkbox"><p> paragraph</p>

jQuery:

$('ul.list').on("click", "input", function() {
    if ( $(this).is(':checked') ) {
        $(this).find('p').css("text-decoration", "line-through");
    } else {
        $(this).find('p').css("text-decoration", "none");
    }
});
adelphus
  • 10,116
  • 5
  • 36
  • 46
Duc Hop Tran
  • 51
  • 1
  • 2
  • 8

4 Answers4

2

The <input> element is a void element (see this answer) and as such is not expected to contain any elements. You can use .next() or .siblings() instead to get the effect you want.

$('ul.list').on("click", "input", function(){
  if( $(this).is(':checked') ) {
    $(this).next('p').css("text-decoration" ,  "line-through");
  } else {
    $(this).siblings('p').css("text-decoration", "none");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
  <li>
    <input type="checkbox"><p> paragraph</p>
  </li>
</ul>
Community
  • 1
  • 1
Erik Inkapööl
  • 378
  • 2
  • 11
2

You can use CSS only solution for that behaviour:

input[type=checkbox]:checked + p {
  text-decoration: line-through;
}
<ul class="list">
  <li>
    <input type="checkbox">
    <p>paragraph</p>
  </li>
</ul>
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • that's good but i append checkbox by click button function and this doesn't working. don't worry i had just found the solution. :D thanks! – Duc Hop Tran Aug 11 '15 at 18:33
  • @ĐứcHợpTrần that handles any dynamic element so you are doing something wrong – A. Wolff Aug 11 '15 at 18:39
1

Your paragraphs aren't inside your input tags. Try using next instead of find:

$('ul.list').on("click", "input", function(){

    if( $(this).is(':checked') ) {
        $(this).next('p').css("text-decoration" ,  "line-through");
    } else {
        $(this).next('p').css("text-decoration", "none");
    }
});

https://api.jquery.com/next/

rrk
  • 15,677
  • 4
  • 29
  • 45
Ben Cook
  • 1,654
  • 2
  • 18
  • 32
0

Use next() function.

 $('ul.list').on("click", "input:checkbox", function () {
    $(this)
        .next('p')
        .css("text-decoration", this.checked ? "line-through" : "none");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul class="list">
  <li>
    <input type="checkbox">
    <p>paragraph</p>
  </li>
</ul>

or you can you use siblings() function

$('ul.list').on("click", "input", function() {
    $(this).siblings('p')
        .css("text-decoration", this.checked ? "line-through" : "none")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul class="list">
  <li>
    <input type="checkbox">
    <p>paragraph</p>
  </li>
</ul>
rrk
  • 15,677
  • 4
  • 29
  • 45