1

I have some dynamic data in my <div> element. Look at the sample below:

<div>345</div>
<div>3245</div>

When I click on the div element, the nested value will change.

var someVar = $(this).find(div);
    someVar.empty();
    someVar.append("<div>Number has changed</div>");

Sample:

 <div>345</div>
 <div>Number has changed</div>

And when I click again on the div, I need to return the previous value:

<div>345</div>
<div>3245</div>

Here's the question: How do I keep this value for returning the number every time I click on the div with changed text inside of it?

2
  • you can read jquery documentation here : api.jquery.com Commented Jun 10, 2017 at 14:09
  • you mean $(this).find( "div" ) Commented Jun 10, 2017 at 14:16

2 Answers 2

2

you need create some data attribute store the previous value.The each time click get the data from attribute and restore the current text to attr like this data-prev.No need to append .html() is enought to toggle

updated

$('div').click(function(){
var prev=$(this).html();
$(this).html($(this).data('prev'));
$(this).data('prev',prev)
console.log($(this).data('prev'))
})
.nested{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>345</div>
<div data-prev="<div class='nested'>Number has changed</div>">3245</div>

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

4 Comments

Can I push there html-code? Like <div data-prev='<div>some new data viewed on click</div>'>3245</div>
why you need to push the entire element .Any perticular point on that
Cause I have a data which should disappear on click and then appear on click. Instead of this data will appear the different icons, that are nested inside the entire element
see my upated answer @LabLab
2

You can use jQuery 'data' method.

   $( "div" ).data( "number", 1 )

Then read it with:

  ( $( "div" ).data( "number" ) )

Documentation: https://api.jquery.com/data/

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.