Shrinath Dhatrak Shrinath Dhatrak - 1 month ago 7
Javascript Question

Apply class to <td>

How can I find the class name of the

<p>
element contained within each
<td>
element then add that class to the
<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 to apply to</p>
</td>
<td rowspan="1" colspan="1">
<p class="Hello_orange">Hello Stack Overflow3</p>
</td>
</tr>
</table>


The
<td>
elements would have the classes like 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>

Answer

You can search the table for p tags, then find the closest parent td and assign the class name.

Using plain Javascript:

// convert "Hello_blue" to "blue"
function convertClassName(src) {
    return src.replace(/^.*?_/, "");
}

var pTags = document.querySelectorAll("table p");
for (var i = 0; i < pTags.length; i++) {
    pTags[i].parentNode.className += " " + convertClassName(pTags[i].className);
}

Working demo: http://jsfiddle.net/jfriend00/6bvwu5qL/

Using jQuery:

// convert "Hello_blue" to "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 be run after the DOM has been loaded. That means you either place them in a script tag at the very end of the document or you call them from a function that isn't invoked until after the DOM has been loaded or you call them from an event handler (like onload) that waits until the DOM has been loaded.