www.webdeveloper.com
Recent Articles
  • Finding Slow Running Queries in ASE 15
  • A More Advanced Pie Chart for Analysis Services Data
  • Adobe AIR Programming Unleashed: Working with Windows
  • Performance Testing SQL Server 2008's Change Data Capture Functionality
  • The ABC's of PHP: Introduction to PHP
  • How to Migrate from BasicFiles to SecureFiles Storage
  • Why the Twitter Haters Are Wrong
  • User Personalization with PHP: Beginning the Application
  • Whats in an Oracle Schema?
  • Lighting Enhancement in Photoshop
  •  

    Go Back   WebDeveloper.com > Client-Side Development > JavaScript

    JavaScript JavaScript (not Java) Discussion and technical support, including AJAX and frameworks (JQuery, MooTools, Prototype...)

    Reply
     
    Thread Tools Search this Thread Rate Thread Display Modes
      #1  
    Old 11-07-2009, 03:02 AM
    MiglioreTech MiglioreTech is offline
    Registered User
     
    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!
    Reply With Quote
      #2  
    Old 11-07-2009, 05:02 AM
    astupidname astupidname is offline
    Registered User
     
    Join Date: Oct 2008
    Location: U.S.
    Posts: 588
    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 05:05 AM.
    Reply With Quote
      #3  
    Old 11-07-2009, 05:48 AM
    rnd me's Avatar
    rnd me rnd me is online now
    working on the chain...
     
    Join Date: Jul 2008
    Location: urbana, il
    Posts: 1,274
    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.
    Reply With Quote
      #4  
    Old 11-07-2009, 06:14 AM
    astupidname astupidname is offline
    Registered User
     
    Join Date: Oct 2008
    Location: U.S.
    Posts: 588
    Quote:
    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!
    Reply With Quote
      #5  
    Old 11-07-2009, 08:56 AM
    MiglioreTech MiglioreTech is offline
    Registered User
     
    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!
    Reply With Quote
    Reply

    Bookmarks

    Tags
    convert, javascript, object


    Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
     
    Thread Tools Search this Thread
    Search this Thread:

    Advanced Search
    Display Modes Rate This Thread
    Rate This Thread:

    Posting Rules
    You may not post new threads
    You may not post replies
    You may not post attachments
    You may not edit your posts

    BB code is On
    Smilies are On
    [IMG] code is Off
    HTML code is Off
    Forum Jump


    All times are GMT -5. The time now is 06:46 AM.



    Acceptable Use Policy

    internet.comMediabistrojusttechjobs.comGraphics.com

    WebMediaBrands Corporate Info


    Advertise | Newsletters | Feedback | Submit News

    Legal Notices | Licensing | Permissions | Privacy Policy

    Powered by vBulletin® Version 3.7.3
    Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.