td.appendChild is not a function [duplicate] - javascript

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;

Related

How can I parse a string as html or maybe how can I dynamic add a complex html by clicking a button?

I need to insert this html tree when I click a button
<div class='img-wrapper'> <img id='immagine_preview' width='200px' height='200px' data-id_immagine='1'><button type='button' class='rimuoviImg' ><span class='fa fa-times'></span></button></div>
I tried this code, but it returns me a body tag with my html inside it.
var stringToHTML = function (str) {
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html');
return doc.body;
};
I need to dynamically add the previous html elements before an upload button (I use a before() method with the stringToHTML function inside and it works). There is a simpler way to do this?. Because I learnt that the documen.createElement doesn't work with a complex argument.
Thank to all community to the help they gave me even with my previous questions.
You can create a html variable with template literal and inside that you can write your html semantic then you can use insertAdjacentHTML()
Use a template string to contain the HTML, and when you click the button use insertAdjacentHTML to add it to an existing element.
const str = `
<div class="img-wrapper">
<img id="immagine_preview" width="200px" height="200px" data-id_immagine="1">
<button type="button" class="rimuoviImg">
<span class="fa fa-times"></span>
</button>
</div>
`
// Cache the element you want to markup to appear,
// and the button
const div = document.querySelector('div');
const button = document.querySelector('button');
// Add a click listener to the button, and insert
// the markup to the chosen element.
button.addEventListener('click', () => {
div.insertAdjacentHTML('beforeend', str);
});
<button>Click</button>
<div />
You could just append the HTML to the element's innerHTML:
document.querySelector('button').addEventListener('click', function() {
document.body.innerHTML += `<div class='img-wrapper'> <img id='immagine_preview' width='200px' height='200px' data-id_immagine='1'><button type='button' class='rimuoviImg' ><span class='fa fa-times'></span></button></div>`;
})
<button>Insert HTML</button>

How do I get data inside table / td

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);

How to get sub attribute value using cheerio in javascript

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%

How to target child element in JavaScript [duplicate]

This question already has answers here:
Get immediate first child element
(1 answer)
How to add/update an attribute to an HTML element using JavaScript?
(4 answers)
Closed 6 years ago.
How to target the img element in JavaScript to change img src.
<body>
<div class="cover">
<img src="img.jpg" width="60" height="60">
</div>
</body>
document.querySelector(".cover img").src = "/test/test.jpg";
please visit HTML DOM querySelector() Method for more information (compatibility, ...)
element.querySelector('img') can get you there as well.
var cover = document.getElementsByClassName('cover')[0],
img = cover.querySelector('img');
img.src = 'http://placehold.it/60x60';
<div class="cover">
<img src="img.jpg" width="60" height="60">
</div>
First select you parent class and then using that select your child element.
var a = document.querySelector(".cover");
var b = a.querySelector("img");
b.style.width = "500px";
b.style.height = "500px";
b.src = "https://source.unsplash.com/category/nature";
If you do not want to support legacy browsers you can do with with document.querySelector:
document.querySelector(".cover img").setAttribute("src", "anotherimage.png");

How can I change table navbar with CSS in an extension?

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

Categories

Resources