使用jquery从textarea解析HTML

时间:2017-08-13 18:45:04

标签: javascript jquery html parsing

我想从textarea解析一些html内容,并使用jquery从选定的标签中获取值。我尝试了以下代码,但没有希望。



var a = $('#a').val();
 var dom_nodes = $($.parseHTML(a));
 alert(dom_nodes.find('#ae').html());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<textarea id="a">
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
 <b:if cond='data:skin.vars.body_background.image and data:features.responsiveBackgrounds' id='ae'>
      <b:with value='&quot;body&quot;' var='selector'>
        <b:include cond='not data:view.isPreview' data='skin.vars.body_background.image' name='responsiveImageStyle'/>
      </b:with>
    </b:if>
    </html>  
</textarea>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

改为使用parseXML

&#13;
&#13;
var a = $('#a').val();
var dom_nodes = $($.parseXML(a));
alert(dom_nodes.find('#ae').html());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<textarea id="a">
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
 <b:if cond='data:skin.vars.body_background.image and data:features.responsiveBackgrounds' id='ae'>
      <b:with value='&quot;body&quot;' var='selector'>
        <b:include cond='not data:view.isPreview' data='skin.vars.body_background.image' name='responsiveImageStyle'/>
      </b:with>
    </b:if>
    </html>  
</textarea>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用DomParser获取ae节点。

var xml = document.getElementById('a').value;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xml, "text/xml");
var ae = xmlDoc.getElementById('ae');
console.log(ae.id);
<textarea id="a">
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
 <b:if cond='data:skin.vars.body_background.image and data:features.responsiveBackgrounds' id='ae'>
      <b:with value='&quot;body&quot;' var='selector'>
        <b:include cond='not data:view.isPreview' data='skin.vars.body_background.image' name='responsiveImageStyle'/>
      </b:with>
    </b:if>
    </html>  
</textarea>