简体   繁体   中英

Creating a DOM element from a complicated HTML-string

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

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

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

See this JSFiddle .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM