Nested tag name with getElementsByTagName doesn't work

css, html, javascript, jquery, sorting

Solution

Invalid:

desc_list=document.getElementsByTagName('td p');

You can't pass a css selector to that function, only a tag name like `div`\ `span` `input` etc'.

You might want to use:

desc_list = $('td p');

Since you tagged the question with jQuery, or `document.querySelectorAll` for vanilla js:

desc_list = document.querySelectorAll('td p');

Problem

I have the following div that contains the table and its data queried from database ``` <div id="content"> <table> <tbody> <tr> <th class="header" colspan="2">Food items include:</th> </tr> <tr> <td id="15" class="fruits">Papaya+salt</td> <td><p>This includes papaya and salt</p></td> </tr> <tr> <td class="meat">Baked chicken</td> <td><p>This includes a chicken thide and kethup</p></td> </tr> <tr> <td id="1" class="Juices">Strawberry Sting</td> <td><p>Sugar, color and water</p></td> </tr> <table> </div> ``` That table is defined in a page.aspx and here is my code used to sort that table data alphabetically ``` OldFunc = window.onload; window.onload = OnLoad; function OnLoad(){ try{ var pathName = window.location.pathname.toLowerCase(); if( pathName=="/Resources/Glossary.aspx") { sort_it(); } OldFunc(); } catch(e) { } } function TermDefinition(def_term,def_desc) { this.def_term=def_term; this.def_desc=def_desc; } function sort_it() { var gloss_list=document.getElementsByTagName('td'); var desc_list=document.getElementsByTagName('td p'); var gloss_defs=[]; var list_length=gloss_list.length; for(var i=0;i<list_length;i++) { gloss_defs[i]=new TermDefinition(gloss_list[i].firstChild.nodeValue,desc_list[i].firstChild.nodeValue); } gloss_defs.sort(function(a, b){ var termA=a.def_term.toLocaleUpperCase(); var termB=b.def_term.toLocaleUpperCase(); if (termA < termB) return -1; if (termA > termB) return 1; return 0; }) for(var i=0;i<gloss_defs.length;i++) { gloss_list[i].firstChild.nodeValue=gloss_defs[i].def_term; desc_list[i].firstChild.nodeValue=gloss_defs[i].def_desc; } } ``` Please lookat the the two getElementsByTagName, I think I am misuse its content since nothing is done on the output.

Original source