0

Utilizing jQuery .children...

var strHtml = $(dt.row(row_idx).child()).children().children().html();

...to pass in the following HTML:

<tbody>
  <tr>
    <td>Notes:</td>
    <td>some info</td>
  </tr>
  <tr>
    <td>Assistance Required:</td>
    <td>​Translation, writing and speaking capabilities </td>
  </tr>
  <tr>
    <td>Unit:</td>
    <td>not listed</td>
  </tr>
</tbody>

How do I grab the label cells (<td>Notes:</td>, <td>Assistance Required:</td>, <td>Unit:</td>) and move to their next corresponding value cell to add a colspan property to the <td> and then return the finished html?

The result should look like...

<tbody>
  <tr>
    <td>Notes:</td>
    <td colspan="12">some info</td>
  </tr>
  <tr>
    <td>Assistance Required:</td>
    <td colspan="12">Translation, writing and speaking capabilities </td>
  </tr>
  <tr>
    <td>Unit:</td>
    <td colspan="12">not listed</td>
  </tr>
</tbody>
2
  • I assume you don't have access to the code that is generating the html? Commented Jun 7, 2018 at 20:47
  • Correct, I do not have access to the code generating the html. Commented Jun 7, 2018 at 21:10

1 Answer 1

1

Take your string and load up a temporary element you create in memory only with that string.

You can use the :nth-child() pseudo-class selector to just select the second child <td> element in each row and then use the JQuery .attr() method to add an attribute to those elements:

var strHTML = `<table>
<tbody>
  <tr>
    <td>Notes:</td>
    <td>some info</td>
  </tr>
  <tr>
    <td>Assistance Required:</td>
    <td>​Translation, writing and speaking capabilities </td>
  </tr>
  <tr>
    <td>Unit:</td>
    <td>not listed</td>
  </tr>
</tbody>
</table>`

// Create a temporary element in memory only
var temp = document.createElement("div");

// Load the string into the temp element
$(temp).html(strHTML);

// Now, you can search through the element

$("td:nth-child(2)", temp).attr("colspan", "12"); // Add the attribtue to the second td in each tr
console.log($(temp).html());  // Get the HTML contents of the <table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

2 Comments

I am fairly new to this, so I did not know about td:nth-child(2), but how do I run it against the HTML in my variable strHtml since I need to return the variable with adjusted HTML?
So even though this is incorrect, in my mind the pseudo code is something like strHtml = $(strHTML).$("td:nth-child(2)").attr("colspan", "12");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.