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).

3
  • 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. Commented Aug 5, 2015 at 14:37
  • 1
    that being said, obj will be the div you created with $('<div/>'), and it has no attribute. you probably want obj.find('form') or whatever. Commented Aug 5, 2015 at 14:39
  • Right, right. I completely overlooked that. Thanks so much :) Commented Aug 5, 2015 at 14:44

2 Answers 2

1

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

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

See this JSFiddle.

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

Comments

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'));
    });

1 Comment

you can also get the attribute value directly from html_code variable

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.