0

Is it possible to create a DOM from an HTML string that includes link, style, script and comments?

In my app, the end user will be pasting some form code, for example:

<!-- Start comment -->
<link href="test.css" rel="stylesheet" type="text/css">
<style type="text/css">
    #full_name{background:#fff; }
    /* This is
    another comment*/
</style>
<div>
<form action="process.php" method="post">
Full Name:<input type="text" name="full_name">
</form> 
</div>
<script type='text/javascript' src='test.js'></script>
<!-- End comment -->

This is the jquery code:

$('#html-go').click(function (e) {
    e.preventDefault();
    var html_code = $('#html-code').val(),
        obj = $('<div/>').html(html_code).contents();
    alert(obj.attr("action"));
});

I want to load it into a DOM element for parsing but I get an undefined error. If the form code contains only that between the tags, then everything's OK.

Here's a JSFiddle that shows the error (paste the form code above).

Community
  • 1
  • 1
Damon Malkiewicz
  • 393
  • 5
  • 15
  • 1
    yes, you can stuff any html you want into a .html() call, and the JS engine will slice/dice it into the DOM. just make sure it's VALID html. if you stuff in bad/broken html, the browser will try to correct it as best it can, and probably not do what you think it should be doing. – Marc B Aug 05 '15 at 14:37
  • 1
    that being said, `obj` will be the div you created with `$('
    ')`, and it has no attribute. you probably want `obj.find('form')` or whatever.
    – Marc B Aug 05 '15 at 14:39
  • Right, right. I completely overlooked that. Thanks so much :) – Damon Malkiewicz Aug 05 '15 at 14:44

2 Answers2

1

You need to get your form inside your newly created div:

alert(obj.find('form').attr("action"))

See this JSFiddle.

Reto Aebersold
  • 16,306
  • 5
  • 55
  • 74
0
$('#html-go').click(function (e)
    {
        e.preventDefault();
        var html_code = $('#html-code').val();
        console.log(html_code);
        obj = $('<div/>').html(html_code).contents();
        alert($(html_code).attr('action'));
    });
A.G
  • 48
  • 2