Remove hidden attribute from tr tag - javascript

I am relatively new to coding and I am trying to remove the "hidden" attribute from a tr tag if I press a button. I tried this by using removeAttribute but nothing happens. I tried this with other tags like button to see if the problem is related with the actual tr tag but nothing worked.
This is the html:
<tr class="hidden1"> <!-- hidden -->
<td><img src="/Users/benrodgers/Desktop/Coding/Project/greenArrowUp.png" id="redDown"></td>
<td rowspan="2">
<textarea name="userimp" id="userImp" disabled></textarea>
<button type="button" id="editBTN" onclick="edit()">:</button>
</td>
</tr>
This the JS:
function addComment() {
var addCom = prompt("Add you comment if you have any tips");
if (addCom != null) {
document.myForm.userinp.value = addCom;
document.getElementsByClassName("hidden1").removeAttribute('hidden');
}
}

Method 1: You need to select the first element from the ClassName, since getElementsByClassName returns a collection (kind of array but not exactly) . Also, you need to remove the attribute name which is class not the value :)
Try this:
document.getElementsByClassName("hidden1")[0].removeAttribute("class");
Method 2: You can also remove this class using the below method:
document.querySelector(".hidden1").classList.remove("hidden1")

It seems like that there is no "hidden" attribute on the <tr> which you can remove.
I guess you wanted to remove the "hidden1" class from the <tr>.
In this case you can do the following:
function addComment()
{
var addCom = prompt("Add you comment if you have any tips");
if (addCom != null)
{
document.myForm.userinp.value = addCom;
document.getElementsByClassName("hidden1")[0].classList.remove("hidden1");
}
}
Notice that the document.getElementsByClassName returns with an Array (actually a collection, but it's like Array), so you have to refer to it's member to refer to an actual DOM element.

this should be work for you:
document.getElementsByClassName("hidden1")[0].classList.remove("hidden1");
because getElementsByClassName returns an collection. in this case index 0 be worked.
Note!
but if you have more tr tags in your table the you have to implement an uniqu selector. or dynamic class names.

Related

add onclick event of specific element (without id or class)

I want to get attribute value (data-resource-id) in tag. But this tag don't have id or class. I just need inside show alert when clicked. This is my code:
<table>
<tbody>
<div class="x">
<tr data-resource-id="first"> //will show alert "first" when clicked
<tr data-resource-input="second">//show nothing when clicked
</div>
<div class="y">
<tr data-resource-id="first"> //show nothing when clicked
</div>
this is my javascript code:
$('.x').on('click','????',function(){
var resourceid = $(this).attr('data-resource-id');
alert(resourceid);
})
I don't know what code to write in '????'. What code should i write?
This updated version of your code might work for you
$(document).on('click', '.x [data-resource-id]', function() {
const resourceId = $(this).attr('data-resource-id');
alert(resourceId);
})
Note, your original code had a variable named resource-id — but hyphens are illegal in javascript identifiers. So you must correct that variable name to resourceId instead
'????' became '.x [data-resource-id]' so that clicks to anything matching that selector are handled
var became const for good measure
Corrected tab consistency
Get all the tags that have your attribute and value:
'tr[data-resource-id="first"]'
Get just the first tag that matches your attribute and value:
'tr[data-resource-id="first"]:first'
You can use data attribute as selector. As below
$('.x').on('click','tr[data-resource-id="first"]:first',function(){
var resourceid = $(this).attr('data-resource-id');
alert(resourceid);
})

Get nested element by name

I have a table of elements like this:
<tr id="elementId">
<img name="img" src=""/><br/>
<input name="text" type="text"/><br/>
<input name="button" type="button"/><br/>
</tr>
Each element is exactly the same, except of its id.
I try to update the elements with javascript, but I have no clue how to get the child nodes by their name.
My code:
//get element
var element = list.rows[i];
//update nodes
element.getElementByName("img")[0].src = someImg;
element.getElementByName("text")[0].value = someText;
element.getElementByName("button")[0].value = someOtherText;
The code doesn't work, because element has no function getElementByName.
Is there any other way to get the nodes by their name?
element.querySelector('[name="thename"]') or element.querySelectorAll('[name=2thename"]')
The function is getElementsByName. Elements is plural.
Note that it returns an array-like HTML Collection, so you'll need to grab the first item off it too (with [0]).
Additionally, you might find that your elements aren't actually in your table row as you are missing table cells. Validate your markup: http://validator.w3.org/nu/
In order to select all alements with a tagname in the whole document you may use
listElements = document.getElementsByTagName();
Inside a certain element, you may use
selectedElement = element.getElementsByTagName();
Notice this functions returns an array with the elements selected. If there is only one element, it will be in
listElements[0]
in the first case, or
selectedElement[0]
in the second.

Javascript jQuery . Add class when the same data-date

I have two tables
<table>
<tr>
<td class="myclass" data-date="2015-07-09"> Some text </td>
</tr>
</table>
<table>
<tr>
<td data-date="2015-07-09"> Text </td>
</tr>
</table>
What I want to do is:
Firstly take the class 'myclass' and add to it one new class 'newclass' . I can easily do it by $('.myclass').addClass('newclass');
Secondly I want to search the DOM if there is a < td > which has the same data-date with the .myclass < td > and add also to the newly found < td > the .newclass
Thank you in advance
You can use:
$('td[data-date='+$('.myclass').data('date')+']').addClass('newclass');
This will satisfy the both condition you are looking for. i.e. adding class to both the td elements.
$('.myclass').data('date') will get the date for myclass element. and attribute value selector to target all the td elments that have same data as that of myclass including myclass itself.
You could simply do:
$('.myclass').each(function () {
$('td[data-date="' + $(this).attr('data-date') + '"]').addClass('newclass');
}):
This will add the new class to each element with the same data-date, including the original one with myclass
Also, this would work fine even if you have multiple rows with a myclass - assuming your question was made more basic than your actual need.
Try this
$("td[data-date='2015-07-09']").addClass('myClass');
You can make it more simple if you give an id to your tables.
Like first-table-name and second-table-name.
In this case you will be able to do this with this code:
$("#first-table-name .myclass").each(function() {
$(this).addClass("newClass");
$("#second-table-name td[data-date='" + $(this).data('date') + "']").addClass("newClass");
});

How to get last element in the .find() object by jquery

I have DOM like this:
<div class="parent">
<button class="add-tr">Add</button>
<table class="child">
<tr data="0"></tr>
<tr data="1"></tr>
...
</table>
</div>
<div class="parent">
<button class="add-tr">Add</button>
<table class="child">
<tr data="0"></tr>
<tr data="1"></tr>
...
</table>
</div>
...
When I click on the Add button, I would like to get the value of the data attribute from the last of it own parent class.
I am using this method to get the last element,but it doesn't work.
$('.add-tr').click( function() {
var last = $(this).parent().find('.child:last').attr('data');
alert(last);
})
Any idea why? Or any other suggestion to get the last element in the table?
UPDATE
Yes, I found the problem, turn out is I forgot the 'tr'. Thanks for your guys answer. All your guys giving the correct answer, I wish I can accept all your answers. Thanks
Try this
var last = $(this).parent().find('.child').find('tr').last().attr('data');
In your example you get last table, but you need get last tr
Example
'.child:last' selector will select the last element having child class. As child class is applied to <table>, this selector will select table element, while you want to select last <tr>.
As there is no data attribute on <table>, .attr('data') on it will return undefined.
To get the value of data attribute on last <tr> use the selector tr:last.
var value = $(this) // Button that is clicked
.parent() // Direct parent element i.e. div.parent
.find('.child tr:last') // Get the last <tr> inside .child
.attr('data'); // Get value of data attribute
As the .child element is next to the button, next() can be used to get the table.child element.
var value = $(this) // Button that is clicked
.next('.child') // Next element i.e. table
.find('tr:last') // Get last <tr>
.attr('data'); // Get value of "data" attribute
I'll recommend to use data-* attribute to store data in custom attribute.
<tr data-num="0">Foo</tr>
<tr data-num="1">Bar</tr>
And to get the value of custom data attribute use data()
.data('num')
If you just want to get the index of the last tr, there is no need to store that on element. You can get the index by using the index().
.index()
This will return index of an element. Note that this is zero-based index which is exactly how you want.
$(".parent").click(function(){
$(this + " tr:last-child").attr("data");
});
should do.
Your code was almost correct, you missed tr:last , i.e.:
var last = $(this).parent().find('.child tr:last').attr('data');
DEMO
http://jsfiddle.net/tuga/vr1knxqq/3/
$('.add-tr').click( function(event) {
var last = $(event.target).next().find("tr").last().attr("data");
alert(last);
})
fiddle-example
You can get an array of the tr elements by using find('.child tr')
and to get the last element in that array you can use last().
Putting it all together you have this:
$('.add-tr').click( function() {
var lastTr = $(this).parent().find('.child tr').last(),
lastData = $(lastTr).attr('data');
alert(lastData);
});
I have setup a codepen here http://codepen.io/anon/pen/aOzmKg to show this working.

Select the first element of several sets

I have an awkward problem, due to inheriting a shedload of really, really badly formatted HTML.
Basically I have some table rows like this:
<tr class="odd">...</tr>
<tr class="odd">...</tr>
<tr class="odd">...</tr>
<tr class="even">...</tr>
<tr class="even">...</tr>
<tr class="even">...</tr>
<tr class="odd">...</tr>
<tr class="odd">...</tr>
<tr class="odd">...</tr>
And what I need is a jQuery selector that will give me the first element of each block of classes. Is that clear enough? I'm not sure how else to explain it.
So in the example case I would want rows 1, 4, and 7.
Ive done this so far by selecting every nth child, but Ive now realised this wont work as there wont always be the same number of rows in each block of classes.
Any help you guys can give it appreciated, as always :)
Cheers!
You'll need to employ some strategic use of :not() and adjacent sibling selectors:
$('tr.odd:first-child, tr.even:first-child, tr:not(.odd) + tr.odd, tr:not(.even) + tr.even')
The tr:not(...) + tr... bits select any tr element that's directly preceded by a tr that does not have the same class name. You can't do this dynamically (e.g. with some sort of wildcard), but it's entirely possible if you specify each class name separately. This will ensure you only select the first element in each contiguous group.
The reason the :first-child pseudo is required is simply because + won't match the first child, since it implies a relationship between an element and its preceding sibling. Note that :first-child accounts for the very first tr only. You could replace tr.odd:first-child, tr.even:first-child with simply tr:first-child if every tr element will have exactly one of either class name, but I specify them anyway for clarity's sake.
Last but not least, this doubles as a valid CSS selector, so you can use it in a stylesheet as well if you like.
$('tr.odd:not(.odd+.odd),tr.even:not(.even+.even)')
This just takes any .odd element which isn't following another .odd, and any .even element which isn't following another .even element.
this may help you
$('button').click(function() {
var lastGroup = ''
$('.groups tr').each(function() {
if(lastGroup != this.className) {
$(this).css('background-color', 'red');
lastGroup = this.className;
}
});
});
explanation: loop through all the TR and verify if the class name (this.className) is equal to lastGroup. if not equal, we have a new group (first element of the group). if equal, ignore and continue. this will work with any class name used.
JSFiddle: http://jsfiddle.net/bq7zB/
Loop through and check if the current element matches the last one, otherwise it's the first of its set:
var lastClass = false;
$('tr.odd, tr.even').each({ function() {
lastClass = $(this).attr('class');
if($(this).attr('class') != lastClass){
// Do your conditional stuff here
}
}
var prevClass = '';
$('tr').each(function(){
var thisClass = $(this).attr('class');
if (prevClass === thisClass) {
//do nothing?
} else {
//push in array? do something to the row?
}
});

Categories