I use code below for get the cell value.
alert(document.getElementById("table-body-positions").rows[0].cells[3].innerHTML);
Td value is
<td><a data-action="details"><span><span class="">2019/01/04 13:36:19</span></span></a></td>
I get result this.
<a data-action="details"><span><span class="">2019/01/04 13:36:19</span></span></a>
But I just want to get 2019/01/04 13:36:19
Same problem here for this td.
<td><a data-action="update-limit" data-filter="limit">1.18809 (505.4)<br>$808.64</a></td>
Find each td by tag name and then recursively check its contents until a nodeType TEXT_NODE is found.
This works best if you do not have a fixed HTML structure within your tds as it would appear.
No ids and no classes needed.
function recursiveSearch(elem){
if(elem.nodeType === Node.TEXT_NODE){
//text was discovered
return elem.data.replace("\n", "").trim();
}
const nodes = elem.childNodes;
return Object.keys(nodes).map(key=>recursiveSearch(nodes[key])).join("");
}
const tds = document.getElementsByTagName('td');
const res = Object.keys(tds).map(key=>{
const td = tds[key];
return recursiveSearch(td);
});
console.log(res);
<table>
<td>
<a data-action="details">
<span>
<span class="">2019/01/04 13:36:19</span>
</span>
</a>
</td>
<td>
<a data-action="update-limit" data-filter="limit">
1.18809 (505.4)<br>$808.64
</a>
</td>
</table>
Instead of InnerHTML, you can use innerText
alert(document.getElementById("table-body-positions").rows[0].cells[1].innerText);
It would be easier if you could add a unique id, or class name to the span you are interested in.
Use innerText rather than innerHTML.
console.log(document.getElementsByTagName('td')[0].getElementsByTagName('span')[1].innerText)
<table>
<td><a data-action="details"><span><span class="">2019/01/04 13:36:19</span></span></a></td>
</table>
Your code seems over complicated just to get innerHTML alerts. Here is my solution. Codepen
HTML
<table id = "table-body-positions">
<tr>
<td><a data-action="details"><span><span id = "details">2019/01/04 13:36:19</span></span></a></td>
<td><a data-action="update-limit" data-filter="limit"><span id = "limit">1.18809 (505.4)<br>$808.64</span></a></td>
</tr>
</table>
JS
let details = document.getElementById("details").innerHTML;
let limit = document.getElementById("limit").innerText;
alert(details);
alert(limit);
Related
I am using cheerio library for data scraping. I am trying to get value of tag using below
var sparkLine = $(this)
.find("td")
.eq(7).text;
HTML
<td><img class="sparkline" alt="sparkline" src="https://files.coinmarketcap.com/generated/sparklines/1.png"></td>
It returns undefined as there is no value of td tag and its child tag. Does anyone know how to get img src value here ?
It works well for below HTML
var sparkLine = $(this)
.find("td")
.eq(6).text;
HTML
<td class="no-wrap percent-24h negative_change text-right" data-usd="-4.85" data-btc="0.00" >-4.85%</td>
Applying this code to the two TD tags on your question:
$('td', htmlCode)
.each(function (counter, elem) {
console.log(`#${counter}`);
console.log($(this).html());
});
First tag:
<td>
<a href="/currencies/bitcoin/#charts">
<img class="sparkline"
alt="sparkline"
src="https://files.coinmarketcap.com/generated/sparklines/1.png">
</a>
</td>
// Returns:
#0
<a href="/currencies/bitcoin/#charts">
<img class="sparkline"
alt="sparkline"
src="https://files.coinmarketcap.com/generated/sparklines/1.png">
</a>
** 2. Second tag:**
<td class="no-wrap percent-24h negative_change text-right"
data-usd="-4.85"
data-btc="0.00" >
-4.85%
</td>
// Returns:
#0
-4.85%
This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 6 years ago.
I'm trying to append a child to a td element. here is the HTML I am working with,
<td colspan="8" class="sectionExpandColumn courseResultLL courseResultLR">
<a class="sectionExpand collapsibleCriteria" action=sectionDetail">
sections
</a>
</td>
I want it to be,
<td colspan="8" class="sectionExpandColumn courseResultLL courseResultLR">
<a class="sectionExpand collapsibleCriteria" action=sectionDetail">
sections
</a>
<a class="sectionExpand collapsibleCriteria" action=sectionDetail">
discussion
</a>
</td>
just simply addding a link tag under td, really.
so in my script,
div = table.getElementsByClassName("sectionExpandColumn");
var button = document.createElement("a");
button.setAttribute("class", "sectionExpand.collapsibleCriteria");
button.innerHTML = "Discussion";
div.appendChild(button);
I am getting Uncaught TypeError: div.appendChild is not a function
Why is it?
Update
Thank you for telling me that I'm working with a htmlcollection!
So I added this code,
for (var i=0; i<div.length; i++){
div[i].appendChild(button);
}
But it runs through just fine, but at the end, it only adds the element to the last div. I'm trying to make a sense out of this... Could you tell me why?
In this instance, your variable div is not an element, but an array like object. You can try:
div = table.getElementsByClassName("sectionExpandColumn");
var button = document.createElement("a");
button.setAttribute("class", "sectionExpand.collapsibleCriteria");
button.innerHTML = "Discussion";
div[0].appendChild(button);
Try this simple code:
<td colspan="8" class="sectionExpandColumn courseResultLL courseResultLR">
<a class="sectionExpand collapsibleCriteria" action="sectionDetail">
sections
</a>
</td>
Jquery:
$('.sectionExpandColumn').append('<a class="sectionExpand collapsibleCriteria" action=sectionDetail"> discussion</a>');
Try This
var div = document.getElementsByClassName("sectionExpandColumn");
var button = document.createElement("a");
button.setAttribute("class", "sectionExpand.collapsibleCriteria");
button.innerHTML = "Discussion";
div.innerHTML +=button;
I am currently developing a Chrome extension for my university and I have done most of the things I want to do but I am having difficulty with one thing is that whenever I try to select the first <table> tag which is the navbar in this link I can't seem to hide it and then add my custom navbar using CSS.
Here is my code (I have included random createtextnode that I want to add to give a sense for what I want do or I am trying to do):
CSS
table:nth-child(1)
{
display:none;
}
JavaScript
var note = document.getElementsByName('stud_login')[0];
var par = document.createElement("div");
var tag = document.createElement("a");
var t1 = document.createTextNode(" Hello! Please try to refresh page again if the verification is not filled properly.");
var t2 = document.createTextNode("Click here");
var t3 = document.createTextNode(" Any suggestions? ");
var br = document.createElement("br");
par.setAttribute("class", "info-msg");
par.appendChild(t1);
tag.setAttribute("href", "http://goo.gl/forms/QI8gPMfKML");
tag.setAttribute("target", "_blank");
tag.setAttribute("id", "rahultag");
par.appendChild(t3);
tag.appendChild(t2);
par.appendChild(tag);
note.parentElement.appendChild(par);
Here is the HTML code i want to target and is the first table that occurs:
<table width="100%" height="15%" border="0" align="center" cellpadding="0" cellspacing="0" background="images/banner_bg3.jpg">
<tr>
<td width="25%" align=left>
<img src="images/vit_logo6.jpg" height="76" width="297">
</td>
<td align=center>
<br>
<font size=5 color=#FFFFFF face="Comic Sans MS">
<b>V-TOP</b><br>Student Login
</font>
</td>
</tr>
</table>
To target the first table, then this would likely give you the desired result
var note = document.getElementsByTagName('table')[0];
If the table is not the first element in its parent, you need to use insertBefore instead of appendChild
note.parentElement.insertBefore(par, note);
Side note:
If the table:nth-child(1) { display: none; } won't work, you could use replaceChild to replace the table with your new element
note.parentElement.replaceChild(par, note);
or simply remove it
note.parentElement.removeChild(note);
Note though, that if you are to remove it, do that after you inserted the new, or else there will be no reference where to insert the new.
If you still need to remove before add, read more here how to get the element to be removed's next sibling: https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
I have this code:
<table class="canToggle">
<tr>
<td>
<div class="messagepop pop">
<p class="selection">moss</p>
<p class="selection">gray</p>
<p class="close">Cancel</p>
</div>
<img src="images/gray.jpg" class="wide high image" id="x1y1" />
</td>
...
</tr>
<table>
When I click one of the ps, I need to get the id of the img so that I can change the img src. I have this JQuery:
var $selection = $(this).text();
$selection = "images/" + $selection + ".jpg";
// I need to populate the value of nextImgID for the next line
$(nextImgID).attr('src', $selection);
I can't figure out how to traverse this. I've looked at the api and some questions here, but things depend on sibling relationships. I would appreciate any help.
You can use .closest() to traverse up to td then find image
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
$(this).closest('td').find('img').attr('src', $selection);
You can also use
$(this).closest('div').next('img').attr('src', $selection);
Try this
$(document).on("click","selection",function(){
var parent = $(this).parent(); // messagepopup div
var imgId = parent.next("img:first").attr("id");
});
You can get the img element by parent.next("img:first")
You can try this :
var image = $(this).parents('td').find('img').attr('src', 'url');
Try this:
You can first search for parent 'td' and then you can find image id.
$('p').click(function(){
var imageid =$(this).parents('td').find('img').attr('id');
//in image id you will get your image's id
})
Try this
$("p").click(function() {
alert($(this).parent().siblings().attr("id"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="canToggle">
<tr>
<td>
<div class="messagepop pop">
<p class="selection">moss</p>
<p class="selection">gray</p>
<p class="close">Cancel</p>
</div>
<img src="images/gray.jpg" class="wide high image" id="x1y1" />
</td>
</tr>
<table>
I'm trying to change the style of a <span> by changing its class. I'm evaluating its text value and want it to change the className to 'red' if it's less than 97.7, or to 'green' if it's anything else. I'm evaluating all <span> of class "qadata".
function changeColor() {
var cells = document.getElementsByTagName('span').getElementsByClassName('qadata');
for (var i=0, len=cells.length; i<len; i++) {
if (parseFloat(cells[i].innerHTML) < 97.7){
cells[i].className = 'red';
}
else {
cells[i].className = 'green';
}
}
}
I'm trying to do this in the following HTML table:
<table datasrc='#QA' class="qa">
<thead>
<tr>
<th>Period</th>
<th>Safety</th>
<th>Quality</th>
<th>Shipping</th>
</tr>
</thead>
<tbody>
<tr>
<td class="leftcolumn"><span datafld='Period' width=100%></span></td>
<td><span datafld='Safety' width=100% class="safety"></span></td>
<td><span datafld='Quality' width=100% class="qadata"></span></td>
<td><span datafld='Shipping' width=100% class="qadata"></span></td>
</tr>
</tbody>
</table>
The data is populated using another function prior to calling changeColor(). This is a corporate intranet site, so I'm currently stuck using ie8 or ie10. JavaScript is preferable to jQuery in this instance.
I've been doing HTML and CSS for years, but never got into JavaScript until recently. I tried searching but haven't found a method posted here that works.
I created a jsfiddle that seems to work. I just used the:
document.querySelectorAll('span.qadata')
It changes the class names for the spans with class qadata. http://jsfiddle.net/mYUjL/