开发者

How to get all Div within a table using javascript

开发者 https://www.devze.com 2022-12-25 09:50 出处:网络
Please tell me how can I get array of all Those DIV of specific table whose LANG=\"1\" using Javascript

Please tell me how can I get array of all Those DIV of specific table whose LANG="1" using Javascript

Table structure is like this:

  < table >
 < tr > < td > < div id=1 lang="1" > some metter < /div > < /td >< /tr >
 < tr > < td > < div id=2 lang="2" > some metter < /div > < /td >< /tr >
 < tr > < td > < d开发者_StackOverflowiv id=3 lang="1" > some metter < /div > < /td >< /tr >
 < tr > < td > < div id=4 lang="1" > some metter < /div > < /td >< /tr >
< /table >


You could give the table a unique id and then use the getElementsByTagName function:

var table = document.getElementById('tableId');
if (table == null) return;
var divs = table.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
    var div = divs[i];
    if (div.lang == '1') {
        alert(div);
    }
}


what happend with ol' plain javascript?

var divs = document.getElementsByTagName('table')[0].getElementsByTagName('div');

edit : forgot last part

var divLang = []; 
for(a in divs){
  ((divs[a].getAttribute('lang')) ==1)? divLang.push(divs[a]) : false;
}


This is easiest if you use a library like Prototype, jQuery, Closure, etc., which offer a nearly-full set of CSS3 selectors.

Using Prototype, it would look like this:

var table = /* ...an expression finding the table...*/;
var divs = table.select('div[lang=1]');

So for instance, if you give your table an id of "myTable":

var table = $('myTable');
var divs = table.select('div[lang=1]');

Or just

var divs = $('myTable').select('div[lang=1]');

Using jQuery, if you give that id to your table, it's:

var divs = $('#myTable div[lang=1]');

(Yes, jQuery and Prototype both use $, but for different things.)


Try

$('table[lang="1"]');

or assign them class lets say "divclass" and select them

$('.divclass[lang="1"]');

This is jQuery syntax since someone else posted in prototype

0

精彩评论

暂无评论...
验证码 换一张
取 消