Jquery alternate way of calling :first - javascript

I am using cheerio which is like jQuery for node.js, but :first is not available.
I want to use something like
var title = $(this).find('td:not([rowspan]):first').text();
So when I am grabbing data I can ignore all td elements that have [rowspan]. For most of the data it looks like
<tbody>
<tr>
<td>Title</td>
<td>somethingelse</td>
</tr>
<tr>
<td>Title</td>
<td>somethingelse</td>
</tr>
<tr>
<td>Title</td>
<td>somethingelse</td>
</tr>
<!-- SOMETIMES THERE IS AN UNRELATED TD IN THE FIRST -->
<tr>
<td rowspan="2" style="text-align:center; background:#ffdacc; textcolor:#000;"><b>3</b></td>
<td>Title</td>
<td>somethingelse</td>
</tr>
</tbody>
Since there are no classes I need to grab the $('td:nth-child(1)') or $('td:first') element, but in some cases its actually the second element.

Use .eq(0):
var title = $(this).find('td:not([rowspan])').eq(0).text();

You need to use the :first-child or :first-of-type and not :first:
var title = $(this).find('td:not([rowspan]):first-child').text();
var title = $(this).find('td:not([rowspan]):first-of-type').text();
If the above both doesn't work, you need to loop through to satisfy the stuff and once done, you can break.

maybe you can use .eq(0) to get the first element of the colection
$('td').eq(0)

If this is referring to the tr then you can use .first()
var title = $(this).find('td:not([rowspan])').first().text();

you can use nth-child(1)
var title = $(this).find('td:not([rowspan]):nth-child(1)').text();

Related

How to access specific tr and td from a tbody without jQuery?

I'm trying to access the first tr and from it the second and third td element. However, I want to achieve this without the usage of jQuery or any other library. I already tried accessing it by using .childNodes[1] or by trying to treat it as an array. I want to know how to do this in general so I can apply it for other tables aswell (in case I want to access a different tr)
The tbody:
<tbody>
<tr role="row" class="odd">
<td>0</td>
<td>15</td>
<td>200</td>
</tr>
</tbody>
A HTMLTableElement element contains a rows property and a HtmlTableRowElement has a cells property. Both are collections.
Alternatively you can use document.querySelectorAll to retrieve (an array of) cells within the first row and subsequently retrieve the last two of those.
You can also get the targeted cells using one css query (last alternative).
const firstRow = document.querySelector(`table tbody`).rows[0];
console.log(firstRow);
const secondTdOfFirstRow = firstRow.cells[1];
console.log(secondTdOfFirstRow);
// alternative
const firstRowLastTwoCells = [...document
.querySelectorAll(`table tbody tr:nth-child(1) td`)].slice(-2);
console.log(firstRowLastTwoCells);
// another alternative
const firstRowLastTwoCellsInOneGo = document
.querySelectorAll(`table tbody tr:nth-child(1) td:not(:first-child)`);
console.log([...firstRowLastTwoCellsInOneGo])
<table>
<tbody>
<tr role="row" class="odd">
<td>0</td>
<td>15</td>
<td>200</td>
</tr>
</tbody>
</table>

How to i change the class name inside <td>

<table id="results">
<thead>
<tr>
<td>1st</td>
<td class="horse1"></td>
</tr>
<tr>
<td>1st</td>
<td class="horse2"></td>
</tr>
<tr>
<td>1st</td>
<td class="horse3"></td>
</tr>
</thead>
</table>
i used this way it didnt worked .
document.getElementById("result").className=horseId;
horseId is an variable and contains value
and there are multiple classes insede so how do i select a specific class to change.
You missed two things; first, you attempted to target by ID result, when you need results. Second, you need to wrap the desired class names in quotes. You can use a variable for the assignment, assuming the variable maps to a string.
It's also worth mentioning that your existing class horse1 is several nodes down from your target ID results. I assume this is the element you're trying to change.
To change the class of the #results element, you can use document.getElementById('results').className = horseId;.
To change the class of the .horse1 element, you can use document.getElementsByClassName('horse1').className = horseId;.
Here's an example of the latter:
var horseId = 'rainbow_dash';
document.getElementsByClassName('horse1').className = horseId;
console.log(document.getElementsByClassName('horse1').className);
<table id="results">
<thead>
<tr>
<td>1st</td>
<td class="horse1"></td>
</tr>
</thead>
</table>
Hope this helps! :)
It should be "results"
document.getElementById("results").className=horseId;

how to get innerhtml close to a span id javascript

Hello guys i am having a problem i am creating a google chrome extension that can exctract some infromation from a website and saving them on a txt file.
The issue is that i want to exctract a innerhtml data close to a span ID this is the code i need to be able to exctract:
<tr class="gridRow_even">
<td class="fieldLabel_150">
Date
</td>
<td>
<span id="123"></span>
12/20
</td>
</tr>
What i want to save is 12/20 on the txt usually i do get element by ID but in this case i have no idea how to get it i tried also doing this using jquery this:
var DT = $("td:contains(/)")
But it gives me object object when i try to save as txt the data exctracted.I have no idea how to do this i am getting crazy please help!!!
const text = Array.prototype.filter.call(document.querySelectorAll('td'), el => el.querySelector('span#a123'))[0].innerText;
console.log(text);
<table>
<tr class="gridRow_even">
<td class="fieldLabel_150">Date</td>
<td>
<span id="a123"></span>
12/20
</td>
</tr>
</table>
Before the explanation, two quick notes about this example:
document.querySelector('td') doesn't appear to work unless it's in a proper table. It's likely your real example is in a <table>, so it's a moot point. If it's not, you'll need to come up with a slightly different method of finding it (which could be the topic of another answer).
123 is not a valid id. An id must begin with a letter. Again, your real target is probably named fine. If it really does start with a number, use el.querySelector('span[id=123]') instead.
As for the code, basically use document.querySelectorAll('td') to get all of the td elements (if they're in a specific table, use that as well, like '#tableId td').
Then, I used Array.prototype.filter() to filter all of the td elements, looking for any that contained the span we want to find. Had to use Array.prototype.filter.call() because the result of document.querySelectorAll() is actually a NodeList, which is array-like, but not an actual array.
Once I have filtered, I just get the first element from the filter and get it's innerText.
If there might be more than one td that has the span in a page, use .map(el => el.innerText) instead of [0].innerText to create an array of all of the values instead.
An alternative would also be to find all of the <span> elements, then loop through and get each of their parentNode elements. This would require though that the <span> is a direct child of the <td>, so may be less flexible depending on your real use case.
const text = Array.prototype.map.call(document.querySelectorAll('span#a123'), el => el.parentNode)[0].innerText;
console.log(text);
<table>
<tr class="gridRow_even">
<td class="fieldLabel_150">Date</td>
<td>
<span id="a123"></span>
12/20
</td>
</tr>
</table>
If you know for sure it'll only ever be one span, you can use this instead:
const text = document.querySelector('span#a123').parentNode.innerText;
console.log(text);
<table>
<tr class="gridRow_even">
<td class="fieldLabel_150">Date</td>
<td>
<span id="a123"></span>
12/20
</td>
</tr>
</table>
Javascript:
var desired_innerHTML = document.getElementById('123').parentElement.innerHTML;
jQuery
var desired_innerHTML = $('#123').parent().html();
12/20 is a text node. You can filter the result of .contents() by .nodeType.
var DT = $("td:contains(/)").contents().filter(function(idx, ele) {
return ele.nodeType == Node.TEXT_NODE && ele.textContent.trim().length != 0;
});
console.log('Txt: ' + DT.text().trim())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="gridRow_even">
<td class="fieldLabel_150">
Date
</td>
<td>
<span id="123"></span>
12/20
</td>
</tr>
<tr class="gridRow_even">
<td class="fieldLabel_150">
Date
</td>
<td>
<span id="xxx"></span>
</td>
</tr>
</tbody>
</table>
This is how you get the expected output
$("span#123").parent().text();
Simple Javascript
document.getElementById("123").parentNode.innerText;

Get a specific column in a table

What I want is to get a specific table column using jquery, so far what I have is this, that selects the first column:
table.find(tr > td:first-child)
But I want to be able to select any column so I can copy it to another table, is there a way to do this for example :
td:n-child
so I can send it the number of column and get all the data from that specific column.
Try this:
for instance for selecting the 2nd element, you would:
table.find("tr > td:nth-child(2)");
table.find("tr > td").eq(n);
I just wrote this from the heart, so I can't confirm if it works, but I think this is the syntax to do this.
:eq() Selector : Description: Select the element at index n within the matched set.
You could use :eq() Selector, e.g :
$('tr > td:eq(n)')
Hope this helps.
$('td:eq(2)').css('background-color','green')
$('tr:eq(2) td:eq(0)').css('background-color','red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1>
<tr>
<td>1</td>
<td>A1</td>
<td>B1</td>
</tr>
<tr>
<td>2</td>
<td>A2</td>
<td>B2</td>
</tr>
<tr>
<td>3</td>
<td>A3</td>
<td>B3</td>
</tr>
</table>

Get ID of first cell in a specific table

Given,
<table id=ThisTable>
<tbody>
<tr>
<td id="ThisCell">
</td>
</tr>
<tr>
<td id="NotThis">
</td>
</tr>
<tr>
<td id="NorThis">
</td>
</tr>
</tbody>
</table
How can I use JQuery/Javascript to assign the ID of the first table cell in #ThisTable to the variable "Selected"?
The result in this case should look like:
var Selected = "ThisCell";
I need to get the first cell's ID without having any knowledge of what the ID is, probably using the :first selector. In addition, this isn't the only table on the page, so it must be referenced with its ID.
var Selected = $('#ThisTable td:first').attr('id');
This selects the first td element that is a descendant of the element with ID ThisTable, returns its id attribute and assigns it to Selected.
JSFiddle
Just:
$("#ThisTable tbody tr:first td:first").attr("id");
This code gets the first td of your table, then stores its id in a variable Selected.
var Selected = document.querySelector("#ThisTable td").id;
Pure DOM methods, fastest method here, and works on 91.71% of browsers according to Can I use.
$(function () {
console.log($($('#ThisTable').find('td')[0]).attr('id'))
});
http://jsfiddle.net/E9mPw/17/

Categories