0

I meet the requirement where i get the js statements from the user and apply to the page

for some reason i have to keep track state of the element

i am facing problem when user gives the statments like

$("someselector").css("color":"red");

or

$("someselector").html("new text");

i will get the statements and apply in page, here i am not able to take the backup of original element

is there any way in jquery where i can call a hook function before calling css , html function and take the element backup

Jai
  • 74,255
  • 12
  • 74
  • 103
thaveethu gce
  • 585
  • 1
  • 9
  • 20
  • 1
    maybe [`.clone()`](https://api.jquery.com/clone/) ? – Qsprec Mar 21 '17 at 12:59
  • but when i can call clone if i get the statement from user and apply – thaveethu gce Mar 21 '17 at 13:16
  • 1
    When you use `var clonedObj = $('some_selector').clone()` you cloned the object to clonedObj. This can be your backup element. After you do the `$("someselector").html("new text");` you still have the clonedObj element with unchanged text. – Qsprec Mar 21 '17 at 13:19
  • Agree,But here selectors are given by the user dynamically, they simply give the input statement like below as $("someselector").html("new text"); , so i (app) cant guess the selector, so cant backup in normal way – thaveethu gce Mar 21 '17 at 13:23
  • Hmm. So I think you should find the selector with regex from the given string. I don't know any other way to achieve this. – Qsprec Mar 21 '17 at 13:30

1 Answers1

1

You can rewrite the css function of jquery to achieve this.

You may need this: What does jQuery.fn mean?

function backup($dom) {
  //console.log("backup dom:", $dom);
  $("h3").after($dom);
}
var fn = {
  css: $.fn.css
};
$.fn.css = function() {
  backup(this.clone());
  return fn.css.apply(this, arguments);
}
$("#a").css("color", "red");
$("#a").css("color", "red");
$("#a").css("color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a">element</div>
<h3>backup:</h3>
Community
  • 1
  • 1
blackmiaool
  • 5,234
  • 2
  • 22
  • 39