JS: Making certain elements hidden via getElementsByClassName - javascript

I'm trying to set up a script that sets invisible everything with a certain class name.
This is an example of what I'm trying to call:
<script type="text/javascript">
function hideItems(){
document.getElementsByClassName('class1').style.visibility = "hidden";
}
</script>
The class names are on the dimensions of a table, similar to this example:
<table onclick="hideItems()" width="200" border="1">
<tr>
<td class="class1">1</td>
<td class="class2">2</td>
<td class="class3">3</td>
<td class="class1">1</td>
<td class="class2">2</td>
<td class="class3">3</td>
</tr>
<tr>
<td class="class3">3</td>
<td class="class1">1</td>
<td class="class2">2</td>
<td class="class3">3</td>
<td class="class1">1</td>
<td class="class2">2</td>
</tr>
</table>
In the end, there's going to be a three checkboxes, displaying the dimensions based on which of the three are selected. That part, I can do just fine, but calling the particular dimensions to become invisible is what I'm having an issue with currently.
Thanks in advance for any kind of help.

getElementsByClassName returns a collection. You can't collectively set properties unless you're using a framwork like jquery
var elems = document.getElementsByClassName('class1');
for(var i = 0; i != elems.length; ++i)
{
elems[i].style.visibility = "hidden"; // hidden has to be a string
}

Related

javascript colspan dynamically while delete cell?

could anyone help me on my code?
I try to make a sample code on the following action:
1. when the user click on the button, the "hello" will take cell 1 and cell 2 while the other cell 3 to 10 will remain.
2. When the user click on the button again, nothing happen.
I try to set a flag to false after the user click on it to let nothing happen if user click again; however, it doesn't work at all. The user can click until the first row's cells deleted just left "hello".
Any solution in javascript or JQuery? I try to search for static variable in javascript but seem impossible.
Thank you in advance.
var flag = false;
function clickhere(){
if(flag = true){
var cell = document.getElementById('a');
document.getElementById("row").deleteCell(1);
cell.setAttribute("colspan", 2);
cell.innerHTML = "hello";
flag=false;
}
}
<table border="1">
<tr id="row">
<td id="a">1</td>
<td id="b">2</td>
<td id="c">3</td>
<td id="d">4</td>
<td id="e">5</td>
</tr>
<tr>
<td id="f">6</td>
<td id="g">7</td>
<td id="h">8</td>
<td id="i">9</td>
<td id="j">10</td>
</tr>
</table>
<input type="button" value="Click" onclick="clickhere();"/>
You have a couple of opportunities to address. Firstly, your if is doing an assignment rather than a a comparison. Since your flag is a boolean we can use it directly. Secondly, your initial assignment and the one at the end of the function should probably be opposite.
Here is one way you might correct things.
var flag = false;
function clickhere(){
if(flag){ return; }
flag = true;
var cell = document.getElementById('a');
document.getElementById("row").deleteCell(1);
cell.setAttribute("colspan", 2);
cell.innerHTML = "hello";
}
<table border="1">
<tr id="row">
<td id="a">1</td>
<td id="b">2</td>
<td id="c">3</td>
<td id="d">4</td>
<td id="e">5</td>
</tr>
<tr>
<td id="f">6</td>
<td id="g">7</td>
<td id="h">8</td>
<td id="i">9</td>
<td id="j">10</td>
</tr>
</table>
<input type="button" value="Click" onclick="clickhere();" />

Show rows in table with cells name attribute containing string from input (JQuery)

I would like to have keyup function that would show only rows matching the input text by cell that spans on multiple rows.
Consider following table:
<table border='1'>
<tr>
<td rowspan='2'>Key1</td>
<td name='Key1'> dummy1 </td>
</tr>
<tr>
<td name='Key1'> dummy2 </td>
</tr>
<tr>
<td rowspan='2'>Key2</td>
<td name='Key2'> dummy3 </td>
</tr>
<tr>
<td name='Key2'> dummy4 </td>
</tr>
</table>
jsfiddle
Here each row has second td tag with name that matches its "parent" column text. So when I type 'Key1' at the input field I would like it to show only dummy1 and dummy2. Is it possible in jquery?
I understand that you want to display the rows that has a matching name. If this is wrong, please elaborate more, then I can update it.
Here is a demo: https://jsfiddle.net/erkaner/gugy7r1o/33/
$('input').keyup(function(){
$('tr').hide();
$("td").filter(function() {
return $(this).text().toLowerCase().indexOf(keyword) != -1; }).parent().show().next().show();
});
});
Here's my take on your issue, assuming you always want the first column to show. https://jsfiddle.net/gugy7r1o/2/
<input type="text" id="myInput" />
<table border='1'>
<tr>
<td rowspan='2'>Key1</td>
<td name='Key1' class="data"> dummy1 </td>
</tr>
<tr>
<td name='Key1' class="data"> dummy2 </td>
</tr>
<tr>
<td rowspan='2'>Key2</td>
<td name='Key2' class="data"> dummy3 </td>
</tr>
<tr>
<td name='Key2' class="data"> dummy4 </td>
</tr>
</table>
.data{
display:none;
}
var theData = $('td.data');
var input = $('#myInput').on('keyup', function(){
theData.hide();
var value = input.val();
var matches = theData.filter('[name="'+value+'"]');
matches.show();
});
Firstly, I would recommend using <ul> to wrap each key in as tables should be used for data structure (Forgive me if that is what it is being used for).
Secondly, just attach an on keyup event to the search box and then find matches based on the id. See example below:
JS Fiddle Demo
It is also worth mentioning that it could be useful attaching a timeout to the keyup event if you end up having large amounts of rows so that only one filter is fired for fast typers!

get data attribute and append optimize

I have been fiddling around and with some code I found here I managed to get some working code although I wonder if it can be optimized further.
I have tried to comment the code so my thought process is shown. If anyone knows a better way to achieve to [get the data-tid attribute and append the value to a span in that tablerow to a td] I would love to hear it.
<table>
<tr data-tid="3"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="2"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="5"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="6"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
</table>
$j = jQuery.noConflict();
$j(document).ready(function() {
topiclistview = $j('[data-tid]').length;
// check if data-tid exists
if (topiclistview > 0) {
//set vars
var tids = $j('[data-tid]');
var tids_array = [];
//get the data attribute values and put them in an array
$j(tids).each(function(index, item) {
tids_array.push($j(item).data('tid'));
});
//run over all tr with the class .col_f_content and append the attribute value
$j('.col_f_content').each(function(index, item){
$j('<span>'+tids_array[index]+'</span>').appendTo($j(item));
//console.log('tr item'+tids_array[index]);
});
}
});
Performance-wise? This is probably a good shot:
// iterate over all elements having the data-tid attribute
$("[data-tid]").each(function() {
// Create our span. No need for a jQuery wrapper.
var span = document.createElement("span");
// Set the span text. No need to involve jQuery's data() function
span.appendChild(document.createTextNode(this.getAttribute("data-tid")));
// Add the span to your second cell (col_f_content). This should be way faster
// than creating a new jQuery object via class selector.
this.cells[1].appendChild(span);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-tid="3">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="2">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="5">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="6">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
</table>
Alternatively, depending upon your needs, you could achieve something similar with CSS only:
tr[data-tid]:after {
display: table-cell;
vertical-align: middle;
content: attr(data-tid);
}
<table>
<tr data-tid="3">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="2">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="5">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="6">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
</table>
I'd try something like this:
$('[data-tid]').each(function(){
var value = $(this).data('tid');
$('<span>' + value + '</span>')
.appendTo($(this).find('.col_f_content'));
});
(PS: Untested)
You don't need to use intermediate arrays, and you can store the set of elements the first time you select them (when you test if there are any elements with [data-tid]).
It should be more performant to select based on a class, so if it's possible to add a class a class to the data-tid element html, we could use that for our selector.
$(document).ready(function() {
'use strict';
// We want to work with these elems
var topiclist = $('[data-tid]');
if (topiclist.length > 0) {
// Just get the data, make a new elem and append it
// All in 1 pass
topiclist.each(function(_, el) {
var $el = $(el);
$el.append('<td>' + $el.data('tid') + '</td>');
});
}
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<table>
<tr data-tid="3"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="2"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="5"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="6"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
</table>
Also note, I'm appending a <td> with your contents to the <tr>, which is the element you selected. <span> is not a legal child of <tr>. If you want to do something with a <span>, you'll need to wrap it in a <td> if it's in a table.

Selecting content with JQuery

Any ideas why this doesn't work?
http://jsfiddle.net/zk4pc/2/
I'm trying to get it so that everytime there is an element with the class "insert_name", the name is printed from the table.
Could you also help me make the selection more advanced (for instance only using the data from the first tr in the "client-profile" class?
Thanks!
HTML
<body onload="printMsg()">
<div id="api_data" style="display:none;">
<div class="client-profile">
<div class="head icon-5">Customer Details</div>
<table id="client-information">
<tbody>
<tr>
<td class="left">Name:</td>
<td class="color">Matthew Tester
</td>
</tr>
<tr class="dark">
<td class="left">E-mail:</td>
<td class="color">asdfg</td>
</tr>
<tr>
<td class="left">Registration:</td>
<td class="color">2013-11-21</td>
</tr>
<tr class="dark">
<td class="left">Status:</td>
<td class="color"><span class="active">Active</span>
</td>
</tr>
<tr>
<td class="left">Last Login Time:</td>
<td class="color" title="2014-05-28 11:43:46">1 hour ago</td>
</tr>
<tr class="dark">
<td class="left">Last Login From:</td>
<td class="color">123.123.123.123</td>
</tr>
<tr>
<td class="left">Location:</td>
<td class="color">United Kingdom</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="insert_name"></div>
</body>
Javascript
(function printMsg() {
var node = document.getElementsByClassName('insert_name');
node.innerHTML = $('[class*="color"]').eq(0).text();
})();
jsFiddle Demo
The issue is with your node selection. When you select by class name it returns an array of elements. Since you are only looking for the div with that class name, access the first index to reference it.
var node = document.getElementsByClassName('insert_name')[0];
edit
To make this iterate all of the nodes you could take this approach
var nodes = document.getElementsByClassName('insert_name');
var text = $('[class*="color"]').eq(0).text();
for(var i = 0; i < nodes.length; i++){
nodes[i].innerHTML = text;
}
Alternatively, since jQuery is already included, you could remove the body's onload event and just use this
jsFiddle Demo
$(function(){
$('.insert_name').html($('[class*="color"]').eq(0).text());
});
To ensure this only acts on the client-profile class the selector would be
$('.insert_name').html($('.client-profile [class*="color"]').eq(0).text());
If you are just trying to insert the name rather than all of the content, this should do the trick:
$(function() {
$('.insert_name').text($('td:contains("Name:")').next().text());
});
Here is the fiddle:
http://jsfiddle.net/b8LKQ/
Hope that helps!
I added a little more jQuery:
$(function() {
$('[class*="color"]').each(function(){
$('.insert_name').append($(this).text());
});
});
http://jsfiddle.net/zk4pc/7/
Hope that helps!

Remove tables from HTML using jQuery

I've got many chunks of HTML coming into my app which I have no control over. They contain tables for layout, which I want to get rid of. They can be complex and nested.
What I want is to basically extract the HTML content from the tables, so that I can inject that into other templates in the app.
I can use jQuery or plain JS only, no server side trickery.
Does anyone know of a jQuery plugin of good tip that will do the job?
Littm - I mean to extract content from the td tags essentially. I want no trace of table left in the code when it's done. Thanks!
Here's an example of the type of HTML in question. It all comes in via XHR from some ancient application so I have no control over the markup. What I want is to get rid of the tables completely, leaving just the rest of the HTML or other text content.
<table>
<tr><td colspan="4"></td></tr>
<tr>
<td width="1%"></td>
<td width="40%" style="padding-left: 15px">
<p>Your access level: <span>Total</span></p>
</td>
<td width="5%">
<table><tr><td><b>Please note</b></td></tr></table>
</td>
<td width="45%" style="padding-left: 6px" valign="top"><p>your account</p></td>
</tr>
<tr><td colspan="4"> </td></tr>
<tr>
<td width="1%"></td>
<td width="40%" style="padding-left: 15px">
<table>
<tr>
<td align="right">Sort Code: </td>
<td align="center"><strong>22-98-21</strong></td>
</tr>
<tr>
<td align="right">Account Number: </td>
<td><strong>1234959</strong></td>
</tr>
</table>
</td>
<td width="5%"></td>
<td width="45%" style="padding-left: 6px">Your account details for</td>
</tr>
</table>
I've tried;
var data = ""
$("td").each(function(){
data += $(this).html()
});
$("article").append(data);
$("table").remove();
But var data still contains nested td tags. I'm no JS expert so I'm not sure what else to try....
Let's suppose that you have X number of tables.
In order to extract all the content information from these, you could try something like this:
// Array containing all the tables' contents
var content = [];
// For each table...
$("table").each(function() {
// Variable for a table
var tb = [];
$(this).find('tr').each(function() {
// Variable for a row
var tr = [];
$(this).find('td').each(function() {
// We push <td> 's content
tr.push($(this).html());
});
// We push the row's content
tb.push(tr);
});
// We push the table's content
content.push(tb);
});
So for instance, if we have the following 2 tables:
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
</tr>
</table>
<table>
<tr>
<td>r1</td>
<td>r2</td>
<td>r3</td>
</tr>
<tr>
<td>rA</td>
<td>rB</td>
</tr>
<tr>
<td>rP</td>
</tr>
</table>
The array content will be something like this:
content = [ [ [1, 2], [A] ] ] , [ [r1, r2, r3], [rA, rB], [rP] ] ]
\_______________/ \______________________________/
1st table 2nd table
and if you want to access the first table, you'll just have to access content[0] for instance.
Now, let's suppose that you have a DIV, with and id my_div, and that you want to output some table content in it.
For example, let's suppose that you only want to have the 1st table only. Then, you would do something like this:
// Note: content[0] = [[1, 2], [A]]
var to_print = "<table>";
for(var i=0; i<content[0].length; i++) {
to_print += "<tr>";
for(var j=0; j<content[0][i].length; j++)
to_print += "<td>"+ content[0][i][j] +"</td>";
to_print += "</tr>";
}
to_print += "</table>";
$("#my_div").html(to_print);
which will give you something like this:
<div id="my_div">
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
</tr>
</table>
</div>
Hope this helps.
Edit: You should create a recursive function to do that.
Simply create you function that gets "td"'s as a value:
function searchTexts(td) {
if (td.find("td")) {
searchTexts(td.find("td"));
}
td.each(function(){
data += $(this).html()
$(this).remove(); // remove it for avoiding duplicates
});
}
Then call it passing a jQuery object to the function.

Categories

Resources