javascript - Apply class to <td> -
how can find class name of <p> element contained within each <td> element add class <td> element's class list?
<table> <tr> <td colspan="1"> <p class="hello_blue">hello stack overflow1</p> </td> <td rowspan="1" colspan="2"> <p class="hello_red">hello stack overflow2</p> <p class="hello_red">defines red color,that class want apply to</p> </td> <td rowspan="1" colspan="1"> <p class="hello_orange">hello stack overflow3</p> </td> </tr> </table> the <td> elements have classes this
<td rowspan="1" colspan="1" class="blue">...</td> <td rowspan="1" colspan="1" class="red">...</td> <td rowspan="1" colspan="1" class="orange">...</td>
you can search table p tags, find closest parent td , assign class name.
using plain javascript:
// convert "hello_blue" "blue" function convertclassname(src) { return src.replace(/^.*?_/, ""); } var ptags = document.queryselectorall("table p"); (var = 0; < ptags.length; i++) { ptags[i].parentnode.classname += " " + convertclassname(ptags[i].classname); } working demo: http://jsfiddle.net/jfriend00/6bvwu5ql/
using jquery:
// convert "hello_blue" "blue" function convertclassname(src) { return src.replace(/^.*?_/, ""); } $("table p").each(function() { $(this).closest("td").addclass(convertclassname(this.classname)); }); working demo: http://jsfiddle.net/jfriend00/36oejbx4/
either of these code blocks should run after dom has been loaded. means either place them in script tag @ end of document or call them function isn't invoked until after dom has been loaded or call them event handler (like onload) waits until dom has been loaded.
Comments
Post a Comment