1

I am in a situation where user can paste any HTML in a textbox. And then I have to manipulate that HTML, e.g, finding out all anchor tags or divs and many more.

To solve the purpose I have made a hidden div and setting the html of that div same as the pasted HTML.

var pastedHtml = $("#textbox-id").val();
$("#hiddendiv").html(pastedHtml);

Once this is done I have full access of that pasted HTML document as DOM element and can manipulate it easily using jQuery or Javascript.

Now the problem I am facing is if there is some kind of class or id or any other selectors which is same as the mother page, whenever I am setting the HTML into the hidden div my mother page is being affected.

So what I am trying somehow encapsulate the CSS style in the pasted HTML, so that it does not affect outer page.

The pasted HTML can contain inline styling (which is not a problem I think), style inside tag or even link from outside file. In fact it can be anything.

So it there any library or something available to do that? Or what should be my approach to solve the issue.

Any help will be very good for me.

Please let me know if any more data is required.

Thanks in advance.

5
  • Set an id to the hidden div element. Then use that id to the selector to select any element inside from the element with that id. Commented Jun 10, 2018 at 12:33
  • What is that? It is not my problem, please take a look at the problem. Commented Jun 10, 2018 at 12:35
  • If you're worried about CSS effecting your mother element, are you also worried about dynamically inserted JS? i.e <script>$("#textbox-id").hide()<script> Commented Jun 10, 2018 at 12:36
  • Yes, you are right, have not thought about that. @plondon Commented Jun 10, 2018 at 12:37
  • 1
    In that case @jancha's solution to use an iframe is the safest approach Commented Jun 10, 2018 at 12:38

2 Answers 2

1

Use iframe. In that case the contents will be fully isolated from the main document.

Also using html(parsedHTML) would look quite insecure to me to use.

Janis

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

Comments

1

If you are in control of assigning the CSS, simply use the hidden div's id when assigning the inner element a CSS.

With that they will generally have a higher specificity and override similar rules.

Sample stack snippet

#hiddendiv #div1 {
  color: red;
}

#hiddendiv .blue {
  color: blue;
}
<div id="hiddendiv">

  <!-- users elements -->

  <div id="div1">Hey, I'm red <span class="blue"> and I am blue </span></div>

</div>


If not, this post might be an alternative, where one isolate the inner elements

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.