0

I am new to jQuery. I need to add a class called "success" to every paragraph in divClass when button btnClassPSuccess is clicked. My HTML code is :-

<div id="divClass">
  <p>A</p>
  <p>B</p>
  <p>C</p>
  <p>D</p>
  <p>E</p>
  <p>F</p>
  <p>G</p>
</div>
<button id="btnClassPSuccess">Change Paragraphs to Success</button>

My jQuery code is :-

$("#btnClassPSuccess").click(function () {
  $('#divClass').addClass("sucess");
});

Can you please correct me how to do this.

2
  • Try this to add class on all paragraph inside a div $("#divClass p").addClass("succcess") Commented Mar 26, 2018 at 2:00
  • If divClass is a class name then use dot instead of # Commented Mar 26, 2018 at 2:04

2 Answers 2

2

You'd do it like:

$("#btnClassPSuccess").click(function () {
    $('#divClass p').addClass("success");
});

Example:

$("#btnClassPSuccess").click(function() {
  $('#divClass').addClass("success");
});
.success {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divClass">
  <p>A</p>
  <p>B</p>
  <p>C</p>
  <p>D</p>
  <p>E</p>
  <p>F</p>
  <p>G</p>
</div>
<button id="btnClassPSuccess">Change Paragraphs to Success</button>

Sign up to request clarification or add additional context in comments.

Comments

0

$("#btnClassPSuccess").click(function () {
  $('#divClass p').addClass("success");
});
.success{
 background: lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divClass">
 <p>A</p>
 <p>B</p>
 <p>C</p>
 <p>D</p>
 <p>E</p>
 <p>F</p>
 <p>G</p>
</div>
<button id="btnClassPSuccess">Change Paragraphs to Success</button>

I see your edit now:

$("#btnClassPSuccess").click(function () {
  $('#divClass p').addClass("success");
});

try it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.