www.webdeveloper.com
Results 1 to 5 of 5

Thread: Javascript Convert String to Object

  1. #1
    Join Date
    Nov 2009
    Posts
    5

    Lightbulb Javascript Convert String to Object

    All -

    I know this has to have been answered thousands of times in the annals of history but:

    if I have a string representation of a select element (dropdown):

    Code:
    var str_select = "<select id='test'><option value='1'>Test</option></select>";
    and I want to treat this an an dropdown object instead of a string, then traverse through the options as such, what is the best way? The same for other elements e.g.
    Code:
    str_div = "<div>Some Code</div>";
    Thanks!

  2. #2
    Join Date
    Oct 2008
    Location
    U.S.
    Posts
    726
    Here is one way you can quickly convert a raw html string (provided it is complete in it's representation of the elements within the string) to an xml object and then can traverse it just like any other xml object, but note it's not directly transferable back to html, you would still need to run through the xml elements and make copies of them as DOM objects, but for what it's worth:
    Code:
    <script type="text/javascript">
    //requires a string of xml text as the txt argument,
    //returns an xml object identical to what would be returned via ajax as responseXML
    function parseXMLString(txt) {
        var i, parser,
            w = window,
            ieParserTypes = [
                "Msxml2.DOMDocument.6.0",
                "Msxml2.DOMDocument.5.0",
                "Msxml2.DOMDocument.4.0",
                "Msxml2.DOMDocument.3.0",
                "Msxml2.DOMDocument.2.0",
                "Microsoft.XMLDOM" //this ones supposedly the same as trying item 5 (version 2.0), but oh well, wanted to keep it
            ];
        if (w.DOMParser) {
            return new w.DOMParser().parseFromString(txt,"text/xml");
        } else if (w.ActiveXObject) {
            for (i = 0; i < ieParserTypes.length; i++) {
                try{
                    parser = new w.ActiveXObject(ieParserTypes[i]);
                    break;
                } catch (er) {}
            }
            parser.async = false;
            parser.loadXML(txt);
            return parser;
        }
    }
    var str = '<select id="thisIsSelectId"><option value="opt0">option 0</option>';
    str += '<option value="opt1">option 1</option>';
    str += '<option value="opt2">option 2</option></select>';
     
    var strToXmlObject = parseXMLString(str);
     
    var selectId = strToXmlObject.getElementsByTagName('select')[0].getAttribute('id');
    alert(selectId);
    var options = strToXmlObject.getElementsByTagName('option');
    alert("options.length = "+ options.length +"\noptions[1].value = "+ options[1].getAttribute('value'));
    </script>
    Last edited by astupidname; 11-07-2009 at 04:05 AM.

  3. #3
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    Code:
    String.prototype.toElement=function(){
     var t=document.createElement("div");
     t.innerHTML=this;
    return t.getElementsByTagName("*")[0];
    }
    
    alert( 
     "<select id='test'>\
       <option value='1'>Test</option>\
       <option value='2'>Test2</option>\
       <option value='3'>Test3</option>\
     </select>".toElement().options[1].value
     );//shows: 2
    this code doesn't linke <html>,<link>, and a couple others.
    for most content chunks, it's just fine.

  4. #4
    Join Date
    Oct 2008
    Location
    U.S.
    Posts
    726
    String.prototype.toElement
    Hey, that is pretty sweet! Definitely falls in to the category of "why didn't I think of that"! And the best part is it appears to translates to DOM easily:
    Code:
    <script type="text/javascript">
    String.prototype.toElement=function(){
     var t=document.createElement("div");
     t.innerHTML=this;
    return t.getElementsByTagName("*")[0];
    }
    var sel = "<select id='test'>\
       <option value='1'>Test</option>\
       <option value='2'>Test2</option>\
       <option value='3'>Test3</option>\
     </select>".toElement();
    alert(sel.options[1].value);
    window.onload = function () {
        var div = document.getElementById('divid');
        div.appendChild(sel);
    };
    </script>
    <div id="divid"></div>
    Way cool!

  5. #5
    Join Date
    Nov 2009
    Posts
    5
    You guys are awesome - I will have jobs lined up for both of you when my company gets bigger. Thanks!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles