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%
Related
<tr><!-- 8 -->
<td id = "8A"><!-- A -->
<img src="Media/empty_square_white.png" height="160px" width ="160px">
</td>
...
<script>
function changeSource(){
document.getElementById("8A").src="empty_square_brown.png";
}
</script>
<button onclick="changeSource">change</button>
This is what I have tried to do however when I press the button nothing seems to happen. I have also tried to do this without the button however that didn't seem to work either, I have defined the id using internal CSS as well. Thanks
Your id references to the surrounding td which has no attribute src. You need to set the id on the img element or reference to the child element.
Also your new value "empty_square_brown.png" is missing the path which is set in the original source "Media/" and the onclick call needs the function brackets. Here some working example. With a title attribute to show the effect.
<tr><!-- 8 -->
<td><!-- A -->
<img id="8A" src="Media/empty_square_white.png" height="160px" width ="160px" title="empty_square_white.png">
</td>
...
<script>
function changeSource(){
document.getElementById("8A").src="Media/empty_square_brown.png";
document.getElementById("8A").title="empty_square_brown.png";
}
</script>
<button onclick="changeSource()">change</button>
You may try this.
function changeImg(){
document.getElementById("image").src = "https://images.unsplash.com/photo-1581618048854-b2f6f877cef3?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80"
}
img{
width:50px;
height:50px;
}
<table border=1>
<tr>
<td >
<img id="image" src="https://images.unsplash.com/photo-1626285094808-143d7bb02f14?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80" alt="" onclick="changeImg()">
</td>
<td>
<img src="#" alt="">
</td>
</tr>
</table>
I am having trouble finding the next element in the DOM with some JavaScript code.
I want to change the img src but when I try to access the img element I get 'null' even though it is there.
Thanks
P
I've tried nextElement and nextElementSibling to no avail
var node1 = document.getElementById('ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinksn0');
console.log('1 ... ' + node1.id);
var node1img = document.getElementById(node1.id).href;
console.log('3 ... ' + node1img);
console.log('3 ... ' + document.getElementById(node1.id).nextElementSibling);
<table cellpadding="0" cellspacing="0" style="border-width:0;">
<tr>
<td>
<a id="ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinksn0" href="javascript:TreeView_ToggleNode(ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinks_Data,0,ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinksn0,' ',ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinksn0Nodes)">
<img src="http://intranetnlb/PublishingImages/plus.gif" alt="Expand <div class='treeviewHeadingPre'></div><div class='treeviewHeading'>An Post Subsidiaries</div>" style="border-width:0;" />
</a>
</td>
</tr>
</table>
I'd hope to find the img tag
The <img> is a child of your a Element. It's not next to it:
node1.getElementsByTagName("img")[0];
Note that document.getElementById(node1.id) is redundant as node1 already contains the element.
Demo by getting the src attribute as example:
var node1 = document.getElementById('ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinksn0');
console.log('1 ... ' + node1.id);
var node1img = node1.href;
console.log('3 ... ' + node1img);
console.log('3 ... ' + node1.getElementsByTagName("img")[0].src);
<table cellpadding="0" cellspacing="0" style="border-width:0;">
<tr>
<td>
<a id="ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinksn0" href="javascript:TreeView_ToggleNode(ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinks_Data,0,ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinksn0,' ',ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinksn0Nodes)">
<img src="http://intranetnlb/PublishingImages/plus.gif" alt="" style="border-width:0;" />
</a>
</td>
</tr>
</table>
Node: The alt tag of your <img> seems to be breaking your markup as it's content isn't escaped properly. Therefore I removed it from the answer.
img is not a sibling which can be accessed with nextElement or nextElementSibling but instead it is a children element of a which can be accessed with .children
So the final code would be
var node1 = document.getElementById('ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinksn0');
console.log('1 ... ' + node1.id);
var node1img = node1.children[0]; // first child which is the img element
<table cellpadding="0" cellspacing="0" style="border-width:0;">
<tr>
<td>
<a id="ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinksn0" href="javascript:TreeView_ToggleNode(ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinks_Data,0,ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinksn0,' ',ctl00_ctl39_g_1398ff2c_c26e_44d8_b382_346b589f7224_tvLinksn0Nodes)">
<img src="http://intranetnlb/PublishingImages/plus.gif" alt="Expand <div class='treeviewHeadingPre'></div><div class='treeviewHeading'>An Post Subsidiaries</div>" style="border-width:0;" />
</a>
</td>
</tr>
</table>
to change the src of the image you can use node1img.src = 'newUrl'!
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);
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>