0

I want to add contents on loading the page and remove the contents while saving to DB.

My response has a

On load:

I got the response and try to put into test field

var element = document.createElement("pp");

var test = $j(element ).attr("id", "exam").addClass("exam");
        test.innerHTML = "test script <div>test</div><script src=\"test.js\" src=\"text/javascript\"></script>";

While accessing test[0].outerHTML i am just getting as

<pp class="exam" id="exam"></pp>

But i am expecting an output as

<pp class="exam" id="exam">test script <div>test</div><script src=\"test.js\" src=\"text/javascript\"></script></pp>

Let me know what's wrong in this

On Save:

I am getting the contents of the text field

 $j("#textfield").html() which has <pp class="exam" id="exam">Test<script src="test.js" src="text/javascript"></script></pp>

now i need to escape the

  <pp class="exam" id="exam"></pp> 

so i used

 $j("#textfield").html().html() which is stripping the <script> tag.

Let me know how i can retain <script/> tag in this case.

2
  • 1
    "I want to add contents on loading the page and remove the contents while saving to DB."—could you explain this a little bit more? It sounds like there's probably a better solution to your problem. Commented Apr 7, 2015 at 11:48
  • While loading the contents of the page i need to put the data inside this temporary tag for visual purpose <pp class="exam" id="exam"></pp> and while save i need to strip of the temporary tag what i added. Commented Apr 7, 2015 at 11:50

3 Answers 3

0

Try with this:

var stringOfHtml = // Your content HTML
$(stringOfHtml).find('script').remove();

How do I use JQuery to remove all "script" tags in a string of HTML?

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

1 Comment

I want to retain the script tags in the response. I updated the description
0

You can encode the <script> tag :

$("<div/>").text(s).html();

And decode it before using it :

$('<div/>').html(text).text();

Comments

0

You can try using vanilla javascript:

var element = document.createElement("pp");
element.id = 'exam';
element.className = 'exam';
element.innerHTML = "test script <div>test</div><script src=\"test.js\" src=\"text/javascript\"></script>";

document.body.appendChild(element);

/* Check contents of <pp id='exam'>*/
var myEl = document.querySelector('#exam').outerHTML;
console.log(myEl);

Output of console.log will be:

<pp id=\"exam\" class=\"exam\">test script <div>test</div><script src=\"test.js\"></script></pp>

Hope that helps! You can read up on how innerHTML vs outerHTML works here: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

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.