开发者

Is there a javascript function that takes a string as input and parse that string asif it is HTML and return me the according element?

开发者 https://www.devze.com 2023-03-22 08:12 出处:网络
Is there a javascript function that takes a string as input and 开发者_如何学Pythonparse that string asif it is HTML and return me the according element?

Is there a javascript function that takes a string as input and 开发者_如何学Pythonparse that string asif it is HTML and return me the according element?

example: F("<div id='outer'><div id='inner'><span hello></span></div></div>") will return me a div HTMLElement that have a child div which in turn has a span child.


No there is no such function. But you can use jQuery $("<div id='outer'><div id='inner'><span hello></span></div></div>") which will do what you want.


Here is a very simple plain javascript solution :

http://jsfiddle.net/7HdJc/1/

function returnTheNodes(htmlStr)
{
var myCont = document.createElement('DIV'); // create a div element
myCont.innerHTML = htmlStr; // create its children with the string 
return myCont.childNodes;  // return the children elements created :)

}


var newElems = returnTheNodes("<div id='outer'><div id='inner'><span hello></span></div></div>");


for(var i = 0; i < newElems.length ; i++ )
{
 alert(newElems[i].id); // newElems[0] has the first DIV

}


And what about DOMParser? Here is an example:

var str = '<div id="outer"><div id="inner"><span> hello</span></div></div>';

function parseStringToDOMElement (str)
{
    var xmlDoc = null;
    if (window.DOMParser)
    {
        var parser = new DOMParser ();
        xmlDoc = parser.parseFromString (str, "text/xml");
    }
    else if (window.ActiveXObject)
    {
        xmlDoc = new ActiveXObject ("Microsoft.XMLDOM");
        xmlDoc.async = false;
        xmlDoc.loadXML (str);
    }
    return xmlDoc.firstChild;

}

var node=parseStringToDOMElement(str);
console.log(node);

I hope it will be helpfull

0

精彩评论

暂无评论...
验证码 换一张
取 消