2013-04-26 31 views
0

如果你不想使用的getElementById檢索一個div的innerHTML(下面看)(考慮到這個網站有幾個DIV與「報價」作爲一個id),但通過參考「字段名」(字段= 「出價」)。你會怎麼做?innerHTML的

<div nowrap="nowrap" id="quote" class="realtimeDetailLayer" source="lightstreamer" 
style="display:inline" table="LS_ProductDetails_TabID" item="X0000010600NL0010379129" 
field="bid">0,28</div> 

我想從現有網站檢索信息。見下面。在這裏你可以看到幾個div有相同的ID

<tbody> 
    <tr> 
    <td style="text-align:right;width:auto;padding:8px 0px;"><nobr>Ref.</nobr>:</td> 
    <td class="ext04" style="white-space:nowrap;width:12%;font-weight:bold;"> 
    EUR 
     <strong><div nowrap=nowrap id="quote" class="realtimeDetailLayer" source="lightstreamer" style="display:inline" table="LS_ProductDetails_TabID" item="X0000010600NL0010379129" field="reference">350,85 
     </div></strong> 
    </td> 
    <td style="text-align:right;width:auto;padding:8px 0px;"><nobr>Bied</nobr>:</td> 
    <td class="ext04" style="white-space:nowrap;width:12%;font-weight:bold;"> 
    EUR 
     <div nowrap=nowrap id="quote" class="realtimeDetailLayer" source="lightstreamer" style="display:inline" table="LS_ProductDetails_TabID" item="X0000010600NL0010379129" field="bid">0,28</div> 
    </td> 
    <td style="text-align:right;width:auto;padding:8px 0px;"> 
     <nobr>Laat</nobr>: 
    </td> 
    <td class="ext04" style="white-space:nowrap;width:12%;font-weight:bold;"> 
    EUR 
     <div nowrap=nowrap id="quote" class="realtimeDetailLayer" source="lightstreamer" style="display:inline" table="LS_ProductDetails_TabID" item="X0000010600NL0010379129" field="ask">0,29 
     </div> 
    </td> 
    <td style="text-align:right;width:auto;padding:8px 0px;"><nobr>%</nobr>:</td> 
    <td class="ext04" style="white-space:nowrap;width:12%;font-weight:bold;"> 
     <div nowrap=nowrap id="quote" class="realtimeDetailLayer" source="lightstreamerGeneratedValues" style="display:inline" table="LS_ProductDetails_TabID" item="X0000010600NL0010379129" field="midchangepercent"><span class="extNegative"><nobr>-50,88 %</nobr></span> 
     </div> 
    </td> 
    </tr> 
</tbody> 
+12

ID應該是唯一的 – Pete 2013-04-26 10:27:31

+0

看看 http://stackoverflow.com/questions/9496427/how-to-get-elements-by-attribute-selector-w-native-javascript-wo-queryselector – 2013-04-26 10:28:55

+2

@Shiju你*可以*在頁面上擁有相同的ID ,但你*不應該*因爲這個原因。 – RemarkLima 2013-04-26 10:29:15

回答

0

你可以通過簡單地解析通過獲取父元素和子元素的DOM來實現。

0

嘗試以下操作:

els = document.getElementsByTagName('div'); 
for (i=0; i<els.length; i++) { 
    if (els[i].field == 'bid') { 
    //do whatever with the bid element here. 
    } 
} 

這得到所有的divs並檢查field屬性。

0

該解決方案是最壞的情況,你沒有任何辦法有元素

唯一的id
var divs = document.getElementsByTagName('div'); 
function getQuoteHtml(key){ 
    var i; 
    for(i =0 ; i < divs.length; i++){ 
     if(divs[i].getAttribute('field') == key){ 
      return divs[i].innerHTML; 
     } 
    } 
} 

演示:Fiddle

0

你可以使用一個CSS選擇這樣做

document.querySelectorAll('[field="bid"]');