Question

I am building a new project and I'm trying to avoid the use of jQuery. I am using Chibi micro-framework which seems very promising.

var container = $('#container');

$().ajax(some_address,'GET',function(data,status){

    container.html(data,'append');

});

The data from the Ajax return is a HTML string. I want to select certain divs from inside the string (the string is giving back the whole html page).

In jQuery I would have done something like:

$('.select_this', data);

How can I achieve this? I believe this can (only?) be done with just javascript.

No correct solution

OTHER TIPS

You can use DOMParser:

var parser = new DOMParser();
var doc = parser.parseFromString(data, 'text/html');

var elements = doc.getElementsByClassName('select_this');

for (var i = 0, len = elements.length; i < len; i++) {
    alert(elements[i].innerHTML);
}

See http://jsfiddle.net/t6w57/4/ for a working example.

Edit: For older browsers, you will need a polyfill (this code is adapted from the DOMParser documentation by the Mozilla Developer Network):

(function(a){var b=a.prototype,d=b.parseFromString;try{return(new a).parseFromString("","text/html")}catch(e){}b.parseFromString=function(a,b){var c;return/^\s*text\/html\s*(?:;|$)/i.test(b)?(c=document.implementation.createHTMLDocument(""),(/<!DOCTYPE/i.test(a)?c.documentElement:c.body).innerHTML=a,c):d.apply(this,arguments)}})(DOMParser);

Non-minified code:

/*
 * DOMParser HTML extension
 * 2012-09-04
 * 
 * By Eli Grey, http://eligrey.com
 * Public domain.
 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 */

/*! @source https://gist.github.com/1129031 */
/*global document, DOMParser*/

(function(DOMParser) {
    "use strict";

    var
      DOMParser_proto = DOMParser.prototype
    , real_parseFromString = DOMParser_proto.parseFromString
    ;

    // Firefox/Opera/IE throw errors on unsupported types
    try {
        // WebKit returns null on unsupported types
        if ((new DOMParser).parseFromString("", "text/html")) {
            // text/html parsing is natively supported
            return;
        }
    } catch (ex) {}

    DOMParser_proto.parseFromString = function(markup, type) {
        if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
            var
              doc = document.implementation.createHTMLDocument("")
            ;
                if (markup.toLowerCase().indexOf('<!doctype') > -1) {
                    doc.documentElement.innerHTML = markup;
                }
                else {
                    doc.body.innerHTML = markup;
                }
            return doc;
        } else {
            return real_parseFromString.apply(this, arguments);
        }
    };
}(DOMParser));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top