Find ID of next instance of a specific class - javascript

I'm trying to find the ID (test1, test2, test3 etc..) of the next instance of a specific class (findMe).
Here is my code:
HTML:
<div class="container">
<table>
<tr id="test1" class="findMe">
<td>
<button class="next">Next</button>
</td>
</tr>
<tr id="test2" class="findMe">
<td>
<button class="next">Next</button>
</td>
</tr>
</table>
<div id="test3" class="findMe">
</div>
</container>
JS:
$(".next").click(function() {
console.log($(this).parent().closest(".findMe").next().attr('id'));
})
I can find the ID "test2" but not "test3". Why?

The second .findMe's nearest ancestor with the third .findMe is a grandparent, not a parent. (The <tr> is inside a <tbody>.)
While you could fix it (kinda) by making your dynamic DOM navigation more flexible, an easier method I think would be to select all .findMes, then access the next index.
const findMes = $('.findMe');
const thisIndex = findMes.index(this);
console.log(findMes[thisIndex + 1]?.id);
You could also use getElementsByClassName, whose collection is live, instead of re-selecting all elements each time.

Related

JS / jQuery - How to load specific HTML element in a variable?

I would like to load all table elements from my index.html which have the specified class assigned in a variable. Unfortunately the first line of HTML doesn't load correctly.
My HTML (example for one table, usually there a few of them):
<!-- More HTML stuff -->
<table class="class_TopTable table" id="id_TopTable">
<tr>
<td>
<button id="id_Remove">Remove 1</button>
</td>
<td>
<div id="id_Title"><B>Title 1</B></div>
<div id="id_Content">Content 1</div>
</td>
</tr>
</table>
<!-- More HTML stuff -->
My Javascript:
var all_class_TopTable = "";
$('.class_TopTable').each(function(){
all_class_TopTable += $(this).html();
})
After this JS is run, the variable of all_class_TopTable containts following HTML:
<tbody>
<tr>
<td>
<button id="id_Remove">Remove 1</button>
</td>
<td>
<div id="id_Title"><B>Title 1</B></div>
<div id="id_Content">Content 1</div>
</td>
</tr>
</tbody>
Where the first line is different as my real html.
I expect in the beginning <table class="class_TopTable table" id="id_TopTable"> and in the end </table>.
But the result is in the beginning <tbody> and in the end </tbody>.
What do I wrong?
You are getting the inner HTML of the table node(s), which excludes the table node(s) itself.
You could wrap all the content in a div and then get its html:
var all_class_TopTable = $('<div>').append($('.class_TopTable').clone()).html();
You could use the outerHTML property to capture the element itself along with its descendants.
all_class_TopTable += $(this)[0].outerHTML;
As the html method only captures its descendants, it wraps it with tbody.

jQuery - how to find a table inside a div

I have the following jsp
<div class="content" id="divContent">
<ul class="ul-content ui-sortable" id="content" style="padding-left: 10px; max-width: 920px;">
<li class="draggable freetext ui-draggable ui-draggable-handle content-element" style="width:; height:; overflow: auto;">
<div class="element-content">
<div class="questiontitle elementtitle" id="58f95b7f-c127-7e40-a3a7-5253ed32fc31">
<table>
<tbody>
<tr>
<td>
<span class="optional1">(Opcional )</span>
</td>
<td>New Freetext Question</td>
</tr>
</tbody>
</table>
</div>
<input class="freetext" type="text" readonly="readonly">
<div class="questionhelp">
</div>
</div>
</li>
</ul>
</div>
I want to find the table inside the div
<div class="questiontitle elementtitle" id="58f95b7f-c127-7e40-a3a7-5253ed32fc31">
I wrote the code:
var contentDivTable = $(contentDiv).find('tr');
var numerocontentDivTable = contentDivTable.length;
console.log('additem after addfreetext contenDiv number table ',numerocontentDivTable);
This is the trace in browser's console
additem after addfreetext contenDiv [object HTMLDivElement]
"additem after addfreetext contenDiv "
<div class="questiontitle elementtitle" id="146b750d-18e8-b8a5-a34d-082c9bd04e0d">New Freetext Question</div>
additem after addfreetext contenDiv number table 0
How can I get the element table?
If you want to select the table inside a div
Apply a css class on div like: <div class="content">
Then use $('.content table') to select table which is inside that div
If you want to check whether there is a table or not, you can do:
if($("#divContent").find('table').length) {
// table exists
} else {
// no table found
}
If divContent have single .questiontitle class div, then you can try as below
var tbl= $("#divContent .questiontitle").find('table');
// this will display full table html content
console.log(tbl.html());
Then if you want to loop over table row data try below code
$(tbl).find('tr').each(function(){
var currentRow=$(this);
var col1_value=currentRow.find("td:eq(0)").text();
var col2_value=currentRow.find("td:eq(1)").text();
});

How do I scan all elements within a class to find a specific id and repeat the process for different ids?

I am quite new to jquery, so please excuse me if I'm doing something stupid:
I have a table where each td belongs to the same class "original" and each one has a unique id.
<table id="main">
<tr>
<td style="cursor: pointer" class="original" id="1">
one
</td>
<td style="cursor: pointer" class="original" id="2">
two
</td>
</tr>
...
...
</table>
I also have a div where all elements are part of a separate class "onclick" and each element has another unique id that is connected to each td from the table.
<div id="second">
<div class="onclick" id="1click">
Extra info about 1
<span class="close" style="cursor: pointer">×</span>
</div>
<div class="onclick" id="2click">
Extra info about 2
<span class="close" style="cursor: pointer">×</span>
</div>
...
...
</div>
When I click on each individual td, I want to display its corresponding div, so if I click on "1" then "1click" shows up. I currently have this jquery code that successfully does this, but only for the first pair of elements, so it doesn't work for anything beyond id="1" and id="1click".
$(function () {
$(".original").click(function() {
var divname = this.id;
if ($(".onclick").attr("id") == divname + 'click'){
var clickname= "#" + divname + "click";
if ($(".hide").css("display") == 'none'){
$(clickname).toggle();
}
}
}
}
How can I make it so that it searches each element of the table to find a match with each element of the div?
Thanks, and sorry if this is a stupid mistake.
I'm finding it difficult understanding what you're trying to do and would love to help but I need to try and understand it better.
1) You can search using .each() which will scan all the elements and you can use a conditional statement to find the one which is needed: I.e.
$(document).ready(function(){
$("td").each(function() {
if ($(this).attr("id") == "2") {
var element = $("#"+$(this).attr("id")+"click");
// do stuff with element
}
})
});
I created a small example which I think helps your scenario on JSFiddle: https://jsfiddle.net/keuhfu36/
$(document).ready(function(){
$("#i2click").click(function() {
alert("hello");
});
$("td").each(function() {
if ($(this).attr("id") == "i2") {
$("#"+$(this).attr("id")+"click").click();
}
});
});
2) I recommend you change the div values from id='1' and id='2' like i did in the example to a value which starts with a letter i.e id="i1" and id="i2" which makes it a lot less of a pain to work with.
Your script should be like ,
$(".original").click(function() {
var divId = this.id,
targetDiv = $("#"+divId+"click");
$(".onclick:visible").hide();
targetDiv.show();
});
Try the following code:
$(function(){
$('.onclick').hide();
$(".original").click(function() {
var divname = this.id;
$('#'+divname+'click').toggle();
});
});
$(function () {
$(".original").click(function() {
// Targeted Div Name
var divname = "#"+ $(this).attr('id') + "click";
// Toggle the div, as Id would be unique in the page
$(divname).toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="main">
<tr>
<td style="cursor: pointer" class="original" id="1">
one
</td>
<td style="cursor: pointer" class="original" id="2">
two
</td>
</tr>
</table>
<div id="second">
<div class="onclick" id="1click">
Extra info about 1
<span class="close" style="cursor: pointer">×</span>
</div>
<div class="onclick" id="2click">
Extra info about 2
<span class="close" style="cursor: pointer">×</span>
</div>
</div>
IMHO, you should ditch the IDs altogether and just use the classes along with their indexes to achieve the desired effect much simpler, like this:
$('#main').on('click', '.original', function() {
var index = $('.original').index($(this)); // find the index of the clicked td
$('.onclick').hide().eq(index).show(); // hide all the divs then show the one at the same index as the clicked td
})
.on('click', '.close', function() {
$('.onclick').hide(); // hide all the divs when "close" is clicked
});
.onclick {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="main">
<tr>
<td style="cursor: pointer" class="original">
one
</td>
<td style="cursor: pointer" class="original">
two
</td>
</tr>
... ...
</table>
<div id="second">
<div class="onclick">
Extra info about 1
<span class="close" style="cursor: pointer">×</span>
</div>
<div class="onclick">
Extra info about 2
<span class="close" style="cursor: pointer">×</span>
</div>
... ...
</div>

Javascript - show hidden table row

I'm brand new to Javascript, and need some help. I have a table with 4 rows (3 displayed, and 1 display="none"). What I'm trying to do is display the 4th row via clicking on a link. Here's what my HTML looks like:
<table class="lessons">
<tr>
<td class="chapter">01</td>
<td class="title-desc"><h3 class="title">INTRODUCTION TO PROGRAM</h3>
<h3 class="desc">Program description....blah blah blah...</h3>
</tr>
<tr>
<td class="chapter">02</td>
<td class="title-desc"><h3 class="title">PARTNER WITH THE PROGRAM</h3>
<h3 class="desc">Description for chapter 2....blah blah...blah...</h3>
</tr>
<tr>
<td class="chapter">03</td>
<td class="title-desc"><h3 class="title">FOCUS ON THE PROGRAM</h3>
<h3 class="desc">Description for chapter 3...blah blah blah....</h3>
</tr>
<tr class="hiddenRow" style="display:none;">
<td class="chapter">04</td>
<td class="title-desc"><h3 class="title">THIS CHAPTER IS HIDDEN</h3>
<h3 class="desc">Chapter four description....blah blah...</h3>
</tr>
</table>
show hidden
And here's my javascript:
function showRows(){
var thisRow = document.getElementsByClassName('hiddenRow');
thisRow.style.display="";
}
Link to JSFiddle:
https://jsfiddle.net/99600cha/
I've tried doing the javascript function a few different ways with no success. Could someone show me what I'm doing wrong?
What I'm really trying to do is have the first and last rows displayed with the middle rows hidden and expandable, like this:
Chapter 1
(click to see all chapters)
Chapter 10
so if anyone can point me to something similar, please do!
Edit: Here is a link that shows the exact effect I'm trying to accomplish: https://www.masterclass.com/classes/aaron-sorkin-teaches-screenwriting
if your are using jquery:
function showRows(){
$('.hiddenRow').hide();
}
In var thisRow = document.getElementsByClassName('hiddenRow'); thisRow returns an array of elements that have such class, you have to use thisRow[0] to select a first element.
However, a more elegant and cleaner solution would be making this layout:
<div class="lessons" id="lessons">
<div class="lesson">
<div class="chapter">01</div>
<div class="title">...</div>
<div class="whatever">...</div>
<div class="whatever">...</div>
</div>
<div class="lesson">
<div class="chapter">01</div>
<div class="title">...</div>
<div class="whatever">...</div>
<div class="whatever">...</div>
</div>
<div class="lesson-hidden">
<div class="chapter">A hidden lesson.</div>
<div class="title">...</div>
<div class="whatever">...</div>
<div class="whatever">...</div>
</div>
</div>
By using this simple CSS rule you will be able to hide all elements by changing a single class:
.lessons .lesson-hidden { display: none; }
.lessons.full .lesson-hidden { display: block; }
To show hidden lessons, use this line:
document.getElementById("lessons").classList.add("full")
To revert, use this line: document.getElementById("lessons").classList.remove("full")

Right way to get the children

I have the below code and it works but what is the right way to get table onclick of add
HTML
<div>
<h4 class="titlebar">
Skills
<small><a onclick="return false;" href="/add/" data-span="3">Add</a></small>
</h4>
<div class="body">
<table class="table">
<tbody>
<tr><td width="125"></td></tr>
</tbody>
</table>
</div>
</div>
JQuery
var TableBlock = $(this).closest('.titlebar').next().children('table');
this points to Add link
You didn't mention who is the parent of <div class="body"> and <h4 class="titlebar"> which is critical.
$(this).closest('table-parent(the missing parent)').find('table');
find is better than childern because it will work even if the table get nested in future development.
If you want only the first matched table:
.find('table').first();
//Or
.find('table:first');
Update:
Based on your question update, I would add to the parent div a class or an id:
<div class="parent" >
<h4 class="titlebar">
...
Then:
$(this).closest('div.parent').find('table');
If you can't change the DOM:
$(this).closest('h4.titlebar').parent().find('table');
Or:
$(this).closest('h4.titlebar').siblings('.body').find('table');

Categories

Resources