How to delete a child and get the parent - javascript

I am not so good with jQuery and I need your help. First, let me explain the situation. I have an HTML table like this :
<table id="table">
<tr><td><img class="image" />test</td><td></td></tr>
<tr><td><img class="image" />test</td><td></td></tr>
</table>
What I need to do is to get the full content of the table : $("#table").html() but without the img tags. (But I do not want to delete them in the original content, only in the "copied" content)
I tried something like that :
$('#table').clone().find('.image').remove().parent().parent().html()
But it is undefined (I guess as the element is removed, I cannot access it and get the parent).
How would you do it ?
Thanks
EDIT: To try to explain it better, the result I would need is :
<table id="table">
<tr><td>test</td><td></td></tr>
<tr><td>test</td><td></td></tr>
</table>

$('#report').clone().find('.plusImage').remove().html() will not return the table's content.
// First clone table and save it to a new variable
var clonedTable = $('#table').clone();
// remove all img tags
clonedTable.find('img').remove();
// test it
console.log(clonedTable.html());
You can also use a regular expression to remove it from the string without cloning DOM:
var contentWithoutImg = $('#table').html().replace(/<img[^>]+\>/ig, '');
console.log(contentWithoutImg);

You can't chain a method for your table to remove() because it returns the element that is removed. Hast has posted the proper answer, but if you think you'll need this more than just once and wanted to create your own method to remove children and return the container, you can use the following:
$.fn.removeDesc = function(sel){
return this.each(function(){
$(this).find(sel).remove();
});
}
You could then use it like so:
var tableHTML = $('#report').clone().removeDesc('.plusImage').html();
JSFiddle

Related

How do I pull data from a HTML table, specifically <td id="word">, using JavaScript?

I have a table that will be populated with data and I need to be able to pull data from specific cells using the cell ID. I have tried using document.getElementById("idName").value but I have now come to understand that the .value is only used with <input> tags. I need the JavaScript code to get the data from the <td> tag, using the ID, and not by hard coding in the information that is in the table as the information will change in that cell.
EDIT: Here is the JavaScript code
'
var RNNo5a = document.getElementById("RN5.5").innerText;
var RNNo5 = document.getElementById("RbR4.4").innerHTML;
var RNN04a = document.getElementById("RN6.4").innerHTML;
//var test;
//if (RNNo5a == RNNo5) {test = RNN04a;}
alert(RNNo5a);
`
The table is filled out by another JavaScript code... could that be the source of my problem?
Try using getElementsById("IdName").innerHTML
The innerHTML property sets or returns the HTML content (inner HTML) of an element.
You can read more on innerHTML here
EDIT RE OP's comment - It works in the below example.
var x = document.getElementById("test").innerHTML;
alert(x);
<p id="test">Hello, World!</p>

change name of DIV width JavaScript

I am using following code:
...
<div id="divcontainer1">
...
<div id="divcontainer2">
...
</div>
</div>
...
Now, I want change "divcontainer2" at a later point of time in the Div "divcontainer3".
What is the right way to check is exist divcontainer2 and when true,
change in divcontainer2 width javascript ?
Thank you,
Hardy
It is probably not nest practice but you can do this by changing the .outterHTML of the element. You would likely want to improve on this but here is a quick example. The last line checks if div 2 exists.
var div2 = document.getElementById("div2");
var html = div2.outerHTML;
var idx = html.indexOf(">");
var newtag = html.substring(0, idx).replace("div2", "div3");
div2.outerHTML = newtag + html.substring(idx, html.length - 1);
var contents = document.getElementById("div3").innerHTML;
alert(document.getElementById("div2") != undefined);
All you do is
get the element .outterHTML
get the substring representing the tag.
Replace the text that defines it
Set the .outterHTML tag to our new string
Now you have a newly named div that keeps all of its attributes, position in the parent and content.
The alert line is how you check for the existence of an object.
I don't believe that there is a "proper" way to do this, however I would store the contents of divcontainer2 in a variable, and then do something like this
var containerOfDivContainer2 = document.getElementById("containerofdiv2");
containerOfDivContaier2.innerHTML = "<div id='divcontainer3'>"/* insert div contents */+"</div>";
Of course, this requires you to put divcontainer2 in a div called containerofdiv2 but it works.
If using jQuery, this will do it:
$('#divcontainer2').attr('id','divcontainer3');
But you shouldn't be changing IDs. Use classes instead and then use the jQuery's toggleClass() function, like:
<div id="divcontainer1">
...
<div id="divcontainer2" class="style1">
...
</div>
$('#divcontainer2').toggleClass("style1 style2");

How to return the result without altering the source?

My HTML and JavaScript code look like this:
<html>
<!--...
many code
...-->
<button onclick="alert($('#mytable').html().wrap('<html/>') );">Show HTML Table</button>
<table id="myTable">
<tr's and td's>
</table>
<!--...
many code
...-->
</html>
I want my javascript to return the table wrapped by the HTML tags but I do not want the table itself to be changed.
You could take a copy of the table first:
$('#mytable').clone()...
To get the actual HTML of the tag you'd need something like this plugin which I posted in another answer yesterday:
(function($) {
$.fn.outerhtml = function() {
return $('<div/>').append(this.clone()).html();
};
})(jQuery);
So you can then do:
alert('<html>' + $('#myTable').outerhtml() + '</html>');
See http://jsfiddle.net/alnitak/2y988/ for a working demo.
This does not work. .html() returns a string, not a jQuery object. So you cannot call wrap on it.
The other problem is that .html() only returns the inner HTML, it does not include the table tag.
You could .clone() the node, attach it to some dummy element and return the .html():
var html = ['<html><body>',
$('<div/>').append($('#mytable').clone()).html(),
'</body></html>'].join('');
Maybe this jQuery outerHTML plugin will help you. It will give you the code for the table, including the enclosing <table> tags. You can maybe do something like alert("<html>" + $("#myTable").outerHtml() + "</html>").
Why not just do the following?:
alert('<html>'+$('#mytable').html()+'</html>');
$("#myTable").wrap("...");
That will wrap the table in the tag supplied to the wrap function, without altering the table itself.
For more information, see the jQuery API for the wrap function.

Adding content to a table row (<TR>) with javascript?

I have a table as follows:
<table>
<tr>
<td>col 1</td><td>col2</td>
</tr>
<tr id="insert">
<td>field</td><td>Field 2</td>
</tr>
<tr>
<td>another field</td><td>one more field</td>
</tr>
</table>
Now the issue is that I need to dynamically insert new rows AFTER the middle row (id = insert). I have a custom javascript function to insert elementsAFTER an element by using an insertBefore call on the next element.
The new rows create successfully using the following javascript:
var new_row = document.createElement('tr');
new_row.innerHTML="<td>test</td>";
insertAfter(document.getElementById("insert"), new_row);
However, the new row refuses to accept any simple html formatting using the innerHTML. The final output of the new row looks something like:
<tr>test</tr>
You see it doesn't want to output the I have specified. The actual script is a lot more complex and so unfortunately manually adding each using an appendChild or similar function would be far too time consuming and probably rather resource intensive. Is there anyway I can just add a 'chunk of html' to this table row and in this chunk define the table columns?
I'm baffled, any help is MUCH appreciated.
You can use the native insertCell() method to insert cells.
Give this a try:
Example: http://jsfiddle.net/VzTJa/
var new_row = document.createElement('tr');
new_row.insertCell(0).innerHTML = "test";
new_row.insertCell(1).innerHTML = "test2";
or you can accomplish it without your insertAfter() function by using insertRow() as well.
Example: http://jsfiddle.net/VzTJa/1/
var insert = document.getElementById("insert");
var new_row = insert.parentNode.insertRow( insert.rowIndex + 1 );
new_row.insertCell(0).innerHTML = "test";
new_row.insertCell(1).innerHTML = "test2";
Give this workaround a try:
Example: http://jsfiddle.net/VzTJa/2/
var temp = '<table><tbody><tr>';
var close_temp = '</tr></tbody></table>';
var temp_div = document.createElement('div');
var html_to_insert = '<td>tester</td><td>tester</td>';
temp_div.innerHTML = temp + html_to_insert + close_temp;
insertAfter(document.getElementById("insert"), temp_div.firstChild.firstChild.firstChild);
temp_div.removeChild(temp_div.firstChild);
Basically creates a couple strings representing the opening and closing tags of a table. You concatenate it with your content, and set it as the innerHTMl of a temporary div, then fetch the row you want, and do an .appendChild().
There may be a better way, or you may find a way to improve this one.
I came up with this after glancing at a solution in this article from a guy who apparently worked on IE and is partly responsible for the parser.
If you can use jQuery, try the append method from it. jQuery append reference
If you do find performance to be an issue, you might find an improvement by building up the dynamic DOM you want to add in javascript before appending it to the actual HTML DOM element that will make it visible. This will keep your number of repaints to a minimum.

Jquery modify div created from html before appending

I have a function that appends a div to another div.
Something like:
var div = ...some html
$("#mydiv").append(div);
However I want to do some stuff to the div I just added. Currently I want to hide a sub part of the new div, and add a object as data. Something like
var div = ...some html
$("#mydiv").append(div);
$(my new div).find(".subDiv").hide();
$(my new div).data('user',object);
But how should I get the the new div I created? Is there a way to create it and then preform these actions, and then append it? Or should I append it and then retrieve it and modify it?
Efficiency is important as this will be iterated for search results...
Thanks!
I used this as my solution thanks to Tricker:
var div = ...a lagre piece of html;
var newDiv = $(div);
newDiv.find("[show='contractor']").hide();
newDiv.data('user', userObject);
$(appendDiv).append(newDiv);
Thanks!
The way u want is like this:
var new_obj = $('<div class="subDiv"></div>');
$("#my_div").append(new_obj);
//You dont have to find the subdiv because the object "new_obj" is your subDiv
new_obj.hide();
new_obj.data('user',object);
Does .append() not return the new item?
var myNewDiv= $("#mydiv").append(div);
since it will always be the last child div, I believe you can access it via $("#myDiv div:last-child")

Categories

Resources