2016-02-06 66 views
0

我有包含HTML元素的文本。例如像這樣Javascript從文本中獲取元素

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

我希望得到一些元素的innerHTML使用類似這樣的例子

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

JavaScript是有可能這樣的文字?或者像這樣的其他方式?

+0

http://www.sitemaps.org/protocol.html - 在最後一章中,有一個架構驗證您的Sitemaps – michi

+0

的[創建從一個新的DOM元素可能的複製HTML字符串使用內置的DOM方法或原型](http://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-方法或親) – isherwood

+0

請告訴我們更多關於你在做什麼 - 你是在瀏覽器中執行此操作還是使用node.js? –

回答

2

你可以使用一個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);

1

根據您的字符串創建一個新元素,如此問題所述:Creating a new DOM element from an HTML string using built-in DOM methods or prototype

之後,您可以使用任何您想要的DOM方法在新的子樹上進行操作。除非要使用取決於實際渲染的方法,否則不需要實際將其附加到頁面上。

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)

+0

我爲您的解決方案創建示例,但它有問題。請參閱https://jsfiddle.net/0uh9c8kp/ – Mohammad

+0

這是正確的想法。唯一的問題是,你不一定「操作......用任何你想要的DOM方法」。節點沒有方法'getElementById'。這是[文檔對象的方法](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)。 –

+0

@JosephMarikle,當然,你仍然受通常規則的約束,只能在元素上調用元素方法。在這個特殊的小提琴'var targetElement = elements.querySelectorAll(「#myId」);'會工作。 –