Search code examples
javascriptextjsextjs4

How to load HTML string as an ExtJS object/element to use selectors


I am using ExtJS 4.2.0 and I was wondering if it's possible to load an HTML string to get an ExtJS object/element in order to use selectors.

In order to be more specific, I will put the following code snippet to understand the situation:

(I am using jQuery since I am more familiar with it and the code is still understandable to show what I'm trying to do with ExtJS).

var html = '<div id="wrapper">' +
    '<div class="sub">One</div>' +
    '<div class="sub">Two</div>' +
    '<div class="sub">Three</div>' +
    '</div>';

var elems = $(html).find('.sub');
console.log(elems);

In the above code snippet, I am loading the HTML string as a jQuery object by doing $(html) and then using selectors by getting all elements that are using .sub CSS class.

However, I've tried the following to replicate the same with ExtJS by using Ext.DomHelper without success.

Live Demo: http://jsfiddle.net/uaBj4/

var obj = Ext.DomHelper.createDom(html);
var arr = Ext.select('.sub', obj);
console.log(arr.elements);

And I was searching over the internet but in many examples they use a listener which affects a component that was already created and then grab the dom element or, in other cases, they use Ext.fly(..) or Ext.select(..) to manipulate an element that already exists in dom which is not my case or what I'm trying to do.


Update: I noticed that I was using Ext.select(..) the wrong way! (like old ExtJS versions). Check API docs for ExtJS 4.2.0: http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-select. Then I just got my obj variable and don't know what more to do.


Solution

  • I finally did it using the following approach.

    Live Demo: http://jsfiddle.net/n36d2/

    // Sample html string
    var html = '<ul id="list">' +
        '<li>One</li>' +
        '<li>Two</li>' +
        '<li>Three</li>' +
        '</ul>';
    
    // Create wrapper html element
    var wrapper = document.createElement('div');
    // Add html string as 'innerHTML'
    wrapper.innerHTML = html;
    // Create 'dom' element
    var dom = Ext.fly(wrapper);
    // Use selector in 'dom' element
    var li = dom.select('#list > li');
    // Print all 'li' elements
    console.log(li.elements);