Remove elements which contain specified content - javascript

I have multiple divs containing tables, one of it is like this:
<div id="apple">
<table width="30%" height="2%" cellpadding="0" border="0px" align="left" >
<tbody>
<tr>
<td style="text-align:center"><font face="Arial"> </font></td>
</tr>
</tbody>
</table>
</div>
Obviously it looks empty but occupies a paragraph in HTML. So I applied JavaScript to remove the table.
var ap = document.getElementById("apple")
if(ap.textContent==" " || ap.textContent==" "){
ap.remove();
}
It seems that I failed to find the "empty" divs. How can I find correctly and remove the whole div?
see fiddle here

You can't call .remove() on a DOM element and I think you are using the non-defined variable div by mistake. Try:
var ap = document.getElementById("apple")
if(ap.textContent==" " || ap.textContent==" ") { //change div for ap
//go to the parent and remove the element
ap.parentNode.removeChild(ap);
}
Your fiddle should look something like this

The textContent will include all the text nodes, the whitespace in the table. Try the following :
var ap = document.getElementById("apple");
if (!ap.textContent.trim()) {
ap.parentNode.removeChild (ap);
}
The is converted to a space in textContent so no need to test for it.
Forked fiddle at http://jsfiddle.net/kQq5b/1/

Here's a solution to your problem, based on your fiddle:
<div id="apple">
<table width="30%" height="2%" cellpadding="0" border="0px" align="left" >
<tbody>
<tr>
<td style="text-align:center"><font face="Arial"> </font></td>
</tr>
</tbody>
</table>
</div>
and JS:
var ap = document.getElementById("apple")
var content = ap.textContent;
content = content.replace(/ /gi, '');
content = content.replace(/\s/g,'');
console.log('Content: "' + content + '"');
if(!content.length){
ap.parentNode.removeChild(ap);
}
Working example: http://jsfiddle.net/orlenko/pvWTP/

Related

jQuery - ForEach function on rendered HTML

I have the following JS/jQuery which grabs the cell value of an ASP DetailsView control (rendered HTML), checks it for a condition, and hides a div based on said condition. It is basically checking to see if the cell value is formatted like an IP address or not...
$(document).ready(function () {
//Grab innerHTML in the IPAddress cell from DetailsView1
//See if it contains the characters: 10.
//If it does not contain '10.', hide the parent div for that user
var ip = document.getElementById("DetailsView1").rows[3].cells[0].innerHTML;
var addrFormat = ip.includes("10.");
if (addrFormat == false) {
$("#IDofDetailsView1ParentDiv").hide();
}
});
This works well, but I need to check several DetailsView controls, and potentially .hide() several elements by ID.
In JS/jQuery, is there a way to:
ForEach rendered HTML element like DetailsView, check format condition, then hide parent div for this control only, if condition is false
Thank you for any advice.
EDITED TO SHOW MARKUP
Here is the rendered HTML I am working with...
<div class="square" id="myId">
<div class="content">
<div><p id="myId2">Unavailable for Dispatch</p>
<div class="table">
<div class="table-cell">
<div id="UpdatePanel1">
<div>
<table class="Grid" cellspacing="0" rules="all" border="1" id="DetailsView1" style="border-collapse:collapse;">
<tr align="center">
<td colspan="2" style="border-style:None;">Text1</td>
</tr><tr align="center">
<td class="building" colspan="2" style="border-style:None;">Text2</td>
</tr><tr align="center">
<td colspan="2" style="border-style:None;">Text3</td>
</tr><tr align="center">
<td class="hide" colspan="2" style="border-style:None;">Text4</td>
</tr><tr align="center">
<td class="hide" colspan="2">Text5</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
I have several of these on my page. Right now I am using:
var ip = document.getElementById("DetailsView1").rows[3].cells[0].innerHTML;
But I will probably need to use a class selector on "Grid" to process them all at once, correct?
Then I need to hide the very highest div by id, not the closest parent. But ONLY hide those divs whose td 'Text 4' value is false. I am not sure how to grab the innerHTML I am currently getting from "DetailsView1", if I use the Grid class instead.
Thank you again...
Uses for each and then use 'this' to target individual elements.
EDIT: Had to edit this and removed includes() as it does not work in very many browsers. Now I am converting the HTML of all .Grid elements toString() and then I use indexOf() on that string to determine if it contains 10.
New working fiddle:
https://jsfiddle.net/Lh5kenge/
Updated Code:
$(function(){
$('.Grid').each(function(){
var string = $(this).html().toString()
console.log(string)
if (string.indexOf("10.") > -1) {
$(this).closest('.square').hide()
}
})
})

html stored in javascript variable,how to Update that html inside javascript variable

Here,
var data = '
<table align="left" border="1" cellpadding="1" cellspacing="1" style="width: 100%;">
<tbody>
<tr>
<td>
<textarea cols="80" id="editor" name="editor" rows="10">This is my textarea to be replaced with Editor.</textarea>
</td>
</tr>
<tr>
<td colspan="2">© 2016 Vishmay Shah</td>
</tr>
</tbody>
</table>
<p> </p>'
I want to update the editor's id to editor1 using jquery within data variable
I can access it using
$('#editor', Data)[0].id=$('#editor', Data)[0].id+'1';
but I want to save updated HTML in the data variable back.
UPDATE
There will be multiple editors with the same id editor.
Actually, I want to make it unique by appending index.
That is editor0,editor1,..., replace function will replace all editor, so it will not help
var editors = $('#editor', Data);
for (var i = 0; i < editors.length; i++) {
var subeditor = editors[i].id + i;
editors[i].id = subeditor;
}
If you have more than one with the same ID name, perhaps you need to find it by attribute and replace the old ID name with index like so :
var Data = '<table align="left" border="1" cellpadding="1" cellspacing="1" style="width: 100%;"> <tbody> <tr><td><textarea cols="80" id="editor" name="editor" rows="10">This is my textarea to be replaced with Editor.</textarea><textarea cols="80" id="editor" name="editor" rows="10">This is my textarea to be replaced with Editor.</textarea></td> </tr> <tr> <td colspan="2">© 2016 Vishmay Shah</td> </tr> </tbody></table><p> </p>';
// this will look the element with ID editor
// and replace element with index
var newElem = $(Data).find('[id="editor"]').attr('id', function(i, old) {
return old + i;
}).end();
console.log(newElem)
DEMO(inspect element to see the actual ID)
This will work out:
Data.replace('name="editor"','name="editor1"')
Updating multiple elements id property can be achieved using :last , .length at .prop(function(name, propertyValue){}) or .attr(function(name, propertyValue){}).
An alternative approach would be to try substituting using same className , e.g.; .editor , for multiple ids beginning with a name and ending in number at multiple elements. Use .length to determine which element currently being processed.

scan table data and replace certain string inside html table

I have following table
<table class="data">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td>
1 data
</td>
<td>
2 data
</td>
<td>
123456789123
</td>
</tr>
</tbody>
</table>
how can I dynamically scan table and replace only values in third table body td values where information like 123456789123 is stored.
This information should be placed with certain character on certain string location so
<td> 123456789123 </td> should be <td> 12345678*12* </td>
Please find below code block for your need, I have added one specific class to TD for which you want to modify value.
$( document ).ready(function() {
$('.value_td').each(function(key, ele){
// Getting Original Value
var original_val = $(ele).text().trim();
// You can change your logic here to modify text
var new_value = original_val.substr(0, 8) + '*' + original_val.substr(9, 2) + '*';
// Replacing new value
$(ele).text(new_value);
});
});
<table class="data">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td>
1 data
</td>
<td>
2 data
</td>
<td class="value_td">
123456789123
</td>
</tr>
</tbody>
</table>
JS Fiddle
To replace the selected texts by indexs, use this:
// replace the 'n'th character of 's' with 't'
function replaceAt(s, n, t) {
return s.substring(0, n) + t + s.substring(n + 1);
}
$('td:nth-of-type(3)').each(function(i, item){
$(this).text($(this).text().trim()); // remove extra spaces
$(this).text(replaceAt($(this).text(), 8, '*')); // replace character in position 8
$(this).text(replaceAt($(this).text(), 11, '*')); // replace character in position 11
});
See the working demo: https://jsfiddle.net/lmgonzalves/6ppo0xp3/
Try this:
$('.data td:nth-child(3n)').text('foo');
This will change every 3rd td’s text inside .data to foo. Here’s a demo: http://jsbin.com/katuwumeyu/1/edit?html,js,output
Let me know if that helps, I’ll gladly adapt my answer in case this isn’t what you need.
You can use jquery ":eq(2)" to track 3rd td position like this:
var el = $('table.data tbody tr td:eq(2)');
el.text(el.text().replace('123456789123','12345678*12*'));
https://jsfiddle.net/v25gu3xk/
or maybe you need to replace char positions:
var el = $('table.data tbody tr td:eq(2)');
var vl = el.text().trim();
el.text(vl.substr(0, 8) + '*' + vl.substr(9, 2) + '*');
https://jsfiddle.net/v25gu3xk/1/

Remove parent element and keep the content

Suppose I have already get the table with JavaScript like this:
var isert = inn.getElementsByTagName("table");
and I've got a structure like this:
<table width="100%">
<tbody>
<tr>
<td><div class="extra"></div>
</td>
</tr>
<tr>
<td><div class="extra"></div>
</td>
</tr>
<tr>
<td><div class="extra"></div>
</td>
</tr>
</tbody>
</table>
Here, how can I remove the outside Table structure, and keep the content only, so that result of the extracted code should be:
<div class="extra"></div>
<div class="extra"></div>
<div class="extra"></div>
Thanks!
I'd suggest:
function removeTo(from, what) {
if (!from || !what) {
return false;
}
else {
els = from.getElementsByTagName(what);
while (els[0]) {
from.parentNode.insertBefore(els[0],from);
}
from.parentNode.removeChild(from);
}
}
removeTo(document.getElementsByTagName('table')[0], 'div');
JS Fiddle demo.
Incidentally:
var isert = inn.getElementsByTagName("table");
Doesn't give you a reference to the table element, it gives you a nodeList of all the table elements within the inn variable (whatever that might be). To act on a particular table you need to specify which particular table you want to act upon, which is why, above, I've used document.getElementsByTagName('table')[0].

IE7 issue with jQuery find?

The following code worked fine in IE7 until I started using IE9.js file. The IE9.js file adds an additional class "ie7_class82" to the already present classes which I added. The code below stopped working in IE7. Is there a known issue with not able to find matching classes with jQuery when multiple classes are present?
--------------HTML code skeleton-------------
<table cellspacing="0" cellpadding="0" bgcolor="#FFF" width="100%">
<thead>
---table rows here----
</thead>
<tbody>
<tr>
<td>
<table cellspacing="0" border="0" width="100%" style="float:left">
<thead>
<tr style="text-align:left;">
<td style="font-size:14px;font-weight:bold;text-align:left;padding:10px 5px">
<span><label class="quarterly">Quarterly</label></span>
<span style="padding:5px">|</span>
<span><label class="monthly">Monthly</label></span>
<span style="padding:5px">|</span>
<span><label class="daily">Daily</label></span>
</td>
</tr>
</thead>
<tbody>
---table rows here----
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<table cellspacing="0" border="0" width="100%" style="float:left" class="quarterly">
---table rows here---
</table>
</td>
</tr>
<tr>
<td>
<table cellspacing="0" border="0" width="100%" style="float:left" class="monthly">
---table rows here---
</table>
</td>
</tr>
<td>
<table cellspacing="0" border="0" width="100%" style="float:left" class="daily">
---table rows here---
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
---------jQuery code--------------
$('table thead span label').click(function() {
$(this).parents('table').parents('table').find('table').hide();
$(this).closest('table').find('tbody tr').hide();
$(this).closest('table').show();
$(this).closest('table').find('tbody tr.' + this.className).show();
$(this).parents('table').parents('table').find('table.' + this.className).show();
});​
Note: Unfortunately no errors in IE7(and works fine in FF and Chrome). It is supposed to hide all the tables and show only the ones which match the class name that is present in the label tag. IE7 hides all the tables but fails to show the tables that match the class.
Updated code(that works in IE7, thanks to SO):
$('table thead span label').click(function() {
var classSelector = $.trim($(this).attr('class')).split(/\s+/g).join(',');
$('label:not('+classSelector+')').css('color','#00425f');
$(this).css('color','#d6c9b9');
$(this).parents('table').parents('table').find('table').hide();
$(this).closest('table').find('tbody tr').hide();
$(this).closest('table').show();
$(this).closest('table').find('tbody tr.' + classSelector).show();
$(this).parents('table').parents('table').find('table.'+ classSelector).show();
});
this.className returns the actual class attribute which, in ie7's case, because of the ie9.js file, contains more than one class.
This means that a selector like the one you use :
'table.' + this.className
will be translated into:
'table.yourClassName ie7_class82'
which is not a valid jquery (or css) selector.
I suggest you replace this.className with something like :
var classSelector = $.trim($(this).attr('class')).split(/\s+/g).join('.');
which means that :
'table.' + classSelector
will be translated into :
'table.yourClassName.ie7_class82.some-other-classes-if-any'
Like one comment mentioned, 'tbody tr.' + this.className will generate an invalid selector if this has more than one class.
It's a little confusing why you're trying to get a row that has a class equal to the label you're clicking on. Perhaps take a look at the DOM navigation methods of jQuery. Specifically parent and parents:
http://api.jquery.com/parent/
http://api.jquery.com/parents/
If you absolutely must do what you're trying to do, then the fix would be to replace spaces with periods in this.className. So you could modify your code to do this:
'tbody tr.' + this.className.replace(/ /g,'.')

Categories