I'm working on a JSP page. When page renders based on certain conditions
1)I have to insert a row to an existing table which has a row with a class name "details" OR 2) delete the inserted row if it exists
Page has to render in ie11 as well. So I cannot use insertAfter() or any es6 methods. I'm unable to append/ remove at the right node
<table id="myTable">
<tr>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
<td>cell 4</td>
</tr>
<tr class="details">
<td>cell 3</td>
<td>cell 4</td>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 7</td>
<td>cell 8</td>
<td>cell 1</td>
<td>cell 2</td>
</tr>
</table>
var newHtml = '<tr class="select__pcp"><td colspan="2"> </td><td class="txt-right">text Msg</td><td class="txt-right span2"></td></tr>';
if(condition) {
// insert newHTML after <tr class="details">
} else {
//if <tr> with class="select__pcp" exists then delete it
}
You need to use appendChild: see this page(https://www.w3schools.com/jsreF/met_node_appendchild.asp)
and removeChild: see this page(https://www.w3schools.com/JSREF/met_node_removechild.asp)
and if you add a node in special place you need to use insertAdjacentElement: see this page(https://www.w3schools.com/jsref/met_node_insertadjacentelement.asp)
To Add: You can try setting the outerHTML of the details element to include the new element.
To Remove: you can set the outerHTML to an empty string
---on snippet load: adds element to table, waits 3 seconds and removes element.
var newHtml = '<tr class="select__pcp"><td colspan="2"> </td><td class="txt-right">text Msg</td><td class="txt-right span2"></td></tr>';
function removeOrAdd(action){
if(action) {
document.querySelector('.details').outerHTML += newHtml
} else {
document.querySelector('.select__pcp').outerHTML = ''
}
}
removeOrAdd(true)
setTimeout(removeOrAdd, 3000, false)
<table id="myTable">
<tr>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
<td>cell 4</td>
</tr>
<tr class="details">
<td>cell 3</td>
<td>cell 4</td>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 7</td>
<td>cell 8</td>
<td>cell 1</td>
<td>cell 2</td>
</tr>
</table>