2013-04-26 43 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"]');