0

I have text that contain HTML elements. For example like this

<div>
    <div>content</div>
    <div>
         <div id="myId">
            <p>
                <span>content</span>
                <span>content</span>
            </p>
        </div>
    </id>   
</div>

I want to get innerHTML of some element from this text using javascript like this example

// HTML variable contain above HTML text
var innerHTML = HTML.getElementById('myId').innerHTML;

Is it possible? Or other way like this way?

Mohammad
  • 21,175
  • 15
  • 55
  • 84

2 Answers2

2

You could use a document fragment.

var HTML = "<div>\
    <div>content</div>\
    <div>\
         <div id=\"myId\">\
            <p>\
                <span>content</span>\
                <span>content</span>\
            </p>\
        </div>\
    </div>\
</div>";

// create a fake document
var df = document.createDocumentFragment();

// create a placeholder node to hold the innerHTML
var el = document.createElement('body');
el.innerHTML = HTML;

// append to the document fragment
df.appendChild(el);

// execute .getElementById
console.log(df.getElementById('myId').innerHTML);
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
1

Create a new element based on your string as described in this question: Creating a new DOM element from an HTML string using built-in DOM methods or prototype.

After that you can operate on your new sub-tree with whatever DOM methods you want. You don't need to actually attach it to the page unless you want to use methods that would depend on actual rendering.

var HTML =
'<div>\
    <div>content</div>\
    <div>\
         <div id="myId">\
            <p>\
                <span>content</span>\
                <span>content</span>\
            </p>\
        </div>\
    </id>\
</div>';

var elements = document.createElement('div');
elements.innerHTML = HTML;
var targetElement = elements.querySelectorAll("#myId");

console.log(targetElement)
Community
  • 1
  • 1
Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
  • I create example for your solution but it has problem. See https://jsfiddle.net/0uh9c8kp/ – Mohammad May 05 '16 at 19:53
  • This is the right idea. The only problem is that you can't necessarily "operate... with whatever DOM methods you want". nodes don't have the method `getElementById`. That is a [method of `document` objects](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById). – Joseph Marikle May 05 '16 at 19:57
  • @JosephMarikle, well of course you're still bound by usual rules and can only call `Element` methods on element. In this particualr fiddle `var targetElement = elements.querySelectorAll("#myId");` will work. – Oleg V. Volkov May 05 '16 at 20:02
  • How can i get `innerHTML` from `targetElement`? – Mohammad May 05 '16 at 20:17