I posted a question a few days ago which worked great and I thank those who helped but for reasons beyond my control I have to classes instead of id's as per my original post.
Basically what I am trying to do is remove the word "Other" from a string (The content is added dynamically through a form).
Here is the code I am trying to use:
var str = document.getElementsByClassName('gv-field-4-custom').innerHTML;
var text = str.replace("Other", " ");
document.getElementsByClassName('gv-field-4-custom').innerHTML = text;
.gv-field-4-custom {
color: #ff0000;
}
<table>
<tr>
<td class="gv-field-4-custom">Complex interventions, Evidence Synthesis (randomised trials), Studies within a Trial (SWAT), Trial Conduct, Trial Design, Other Core Outcome Sets (COS)</td>
</tr>
</table>
Any advise as to what I am doing wrong?
Your problem here is, that getElementsByClassName returns a set of elements, which in this particular case just contains a single element. If you just have a single element with this className, or just want to change one single element, you can go like this:
var element = document.getElementsByClassName('gv-field-4-custom')[0];
var str = element.innerHTML;
var text = str.replace("Other", " ");
element.innerHTML = text;
.gv-field-4-custom {
color: #ff0000;
}
<table>
<tr>
<td class="gv-field-4-custom">Complex interventions, Evidence Synthesis (randomised trials), Studies within a Trial (SWAT), Trial Conduct, Trial Design, Other Core Outcome Sets (COS)</td>
</tr>
</table>
If you have more elements that need a treatment, go like this:
var elements = document.getElementsByClassName('gv-field-4-custom');
for (var i = 0; i < elements.length; i++) {
var str = elements[i].innerHTML;
var text = str.replace("Other", " ");
elements[i].innerHTML = text;
}
.gv-field-4-custom {
color: #ff0000;
}
<table>
<tr>
<td class="gv-field-4-custom">Complex interventions, Evidence Synthesis (randomised trials), Studies within a Trial (SWAT), Trial Conduct, Trial Design, Other Core Outcome Sets (COS)</td>
</tr>
</table>
document.getElementsByClassName('gv-field-4-custom')
will returns an array.You cannot directly get the innerHtml.
use document.getElementsByClassName('gv-field-4-custom')[0].innerHtml to get the value.Use the below code
var str = document.getElementsByClassName('gv-field-4-custom')[0].innerHTML;
var text = str.replace("Other", " ");
Note the s in getElementsByClassName. It means you need to loop over these.
You can use either the code
var className= document.getElementsByClassName("gv-field-4-custom");
for(i=0;i<className.length;i++)
{
className[i].innerHTML = "text";
}
like #saina suggested, or use document.getElementsByClassName('gv-field-4-custom')[0] like #Imran suggested.
var str = document.getElementsByClassName('gv-field-4-custom')[0];
var oldText = str.innerHTML
var text = oldText.replace("Other", " ");
str.innerHTML = text;
try this:
document.getElementsByClassName('gv-field-4-custom')[0]
instead of
document.getElementsByClassName('gv-field-4-custom')
Related
i have a site where i paste my entire source code into a box and update all the td tags with a background color if there isnt currently a "bgcolor" attribute.
I've been messing with this for some time but i can't get my ogSource to update. I've tried many ways such as assigning new variables, returns etc etc. No luck.
the below code properly scans for the appropriate td and adds the background color, it just doesnt apply it to the ogSource. I've removed all my other code to make this as basic as possible.
Can anyone assist with this?
Thanks in advance.
var ogSource = '<table id="test1"> <tr> <td> <table id="test2"> <tr> <td> </td> </tr> </table></td> </tr> </table>'
ogSource.replace(/\<td(.*?)\>/g, function(matches) {
if (!matches.includes('bgcolor')) {
var idx = matches.lastIndexOf(">");
if (idx > -1) {
matches = matches.substr(0, idx) + " bgcolor='pink'" + matches.substr(idx);
}
}
});
console.log(ogSource);
EDIT/UPDATE
After a lot of messing around- this was a solution that was able to capture all the source code pasted and make the modification needed.
ogSource = ogSource.replace(/\<td(.*?)\>/g, function( matches , i ) {
var idx = matches.lastIndexOf(">");
if (idx > -1) {
if (!matches.includes('bgcolor')) {
ogSource = matches.substr(0, idx) + " bgcolor='pink'" + matches.substr(idx);
} else {
ogSource = matches;
}
} return ogSource;
});
console.log(ogSource);
My initial answer was off the mark but quite a bit, however, I think regex in general may not be the best solution due to the amount of edge cases present and the DOMParser might be a better solution for this.
Essentially, you pass the html string into the DOMParser method parseFromString and store that in a variable, then select all td elements and check if they have a bgColor attribute, if they don't, give them one, then output the new DOM string.
Here's an example:
const domParser = new DOMParser();
const DOM = domParser.parseFromString(`<table id="test1"> <tr> <td> <table id="test2"> <tr> <td> </td> </tr> </table></td> </tr> </table>`, "text/html");
// Find all tds
const tds = DOM.querySelectorAll("td");
for(let i = 0; i < tds.length; i++) {
let currentTD = tds[i];
if(!currentTD.hasAttribute("bgColor")) {
currentTD.setAttribute("bgColor", "someValue");
}
}
console.log(DOM.body.innerHTML); // If you only want to return the table content
console.log(DOM.querySelector("html").innerHTML); // If you want all of the html code that was added
I have a string of text here that will be dynamically generated to be one of the following:
<h1 id="headline">"Get your FREE toothbrush!"</h1>
OR
<h1 id="headline">"FREE floss set and dentures!"</h1>
Since this will be dynamically generated I won't be able to wrap a <span> around the word "FREE" so I want to specifically target the word "FREE" using Javascript so that I can style it with a different font-family and font-color than whatever styling the <h1> is set to. What methods do I use to go about doing this?
You can search and replace the substring 'FREE' with styled HTML. If 'FREE' occurs more than once in the string you may need to use regex (unless you don't need to support Internet Explorer). See How to replace all occurrences of a string?
In your case:
let str = '<h1 id="headline">"FREE floss set and dentures!"</h1>'
str = str.replace(/FREE/g, '<span color="red">FREE</span>');
The property you are looking for is innerHTML, look the following example:
var word = document.getElementById('word');
function changeWord(){
word.innerHTML = "another";
word.style.backgroundColor = 'black';
word.style.color = 'white';
}
<h1 id="headline">
<span id="word">some</span> base title
</h1>
<button onClick="changeWord()">
change
</button>
Here is a working example using slice and some classic concatenation.
EDIT: Code for the second string is also included now.
//get headline by id
var headline = document.getElementById("headline");
//declare your possible strings in vars
var string1 = "Get your FREE toothbrush!"
var string2 = "FREE floss set and dentures!"
//declare formatted span with "FREE" in var
var formattedFree = "<span style='color: blue; font-style: italic;'>FREE</span>"
//target positions for the rest of your string
var string1Position = 13
var string2Position = 4
//concat your vars into expected positions for each string
var newString1 = string1.slice(0, 9) + formattedFree + string1.slice(string1Position);
var newString2 = formattedFree + string2.slice(string2Position)
//check if strings exist in html, if they do then append the new strings with formatted span
if (headline.innerHTML.includes(string1)) {
headline.innerHTML = newString1
}
else if (headline.innerHTML.includes(string2)) {
headline.innerHTML = newString2
}
<!-- As you can see the original string does not have "FREE" formatted -->
<!-- Change this to your other string "FREE floss set and dentures!" to see it work there as well -->
<h1 id="headline">Get your FREE toothbrush!</h1>
You can split the text and convert the keyword "FREE" to a span element. So you can style the keyword "FREE". This method is safe because does not alter any non-text html element.
var keyword = "FREE";
var headline = document.getElementById("headline");
var highlight, index;
headline.childNodes.forEach(child => {
if (child.nodeType == Node.TEXT_NODE) {
while ((index = child.textContent.indexOf(keyword)) != -1) {
highlight = child.splitText(index);
child = highlight.splitText(keyword.length);
with(headline.insertBefore(document.createElement("span"), highlight)) {
appendChild(highlight);
className = 'highlight';
}
}
}
});
.highlight {
/* style your keyword */
background-color: yellow;
}
<div id="FREE">
<h1 id="headline">"Get your FREE toothbrush! FREE floss set and dentures!"</h1>
</div>
I want to add numbers in <td></td> below via JavaScript. For example using the following description:
<td id='last'> + formatNumber(data.tickers[key].last) + </td>
<td id='high'> + formatNumber(data.tickers[key].high) + </td>
<td id='low'> + formatNumber(data.tickers[key].low) + </td>
How do I change the text of table data elements via JavaScript?
<td id='new1'> = + <td id='last'> + <td id='high'> + </td>
<td id='new2'> = + <td id='high'> + <td id='loww'> + </td>
Try this:
// these target the cell elements
let last = document.getElementById("last");
let high = document.getElementById("high");
let low = document.getElementById("low");
let new1 = document.getElementById("new1");
let new2 = document.getElementById("new2");
// now we convert cell content to numbers, add them and make them 2 decimal places.
new1.textContent = (parseFloat(last.textContent) + parseFloat(high.textContent)).toFixed(2);
new2.textContent = (parseFloat(high.textContent) + parseFloat(low.textContent)).toFixed(2);
td {
border: solid 1px;
}
<table>
<tr>
<th>last</th>
<th>high</th>
<th>low</th>
<th>new1</th>
<th>new2</th>
</tr>
<tr>
<td id='last'> 23.40 </td>
<td id='high'> 28.20 </td>
<td id='low'> 22.10 </td>
<td id='new1'></td>
<td id='new2'></td>
</tr>
</table>
First I'm going to make your life a bit easier. Instead of using document.getElementsByTagName('tr')[3].getElementsByTagName('td')[2] to get the fourth tr element's third td element ([0] = first, [2] = third, etc) this will help make your code much much easier to read. You don't need id attributes on every element if you know how reliable code and order are by default.
function tag_(t)
{//Example: tag_('body')[0];
return (document.getElementsByTagName(t)) ? document.getElementsByTagName(t) : false;
}
Object.prototype.tag_ = function(t)
{//Example: id_('unique_id').tag_('td')[0];
return (this.getElementsByTagName && this.getElementsByTagName(t) && this.getElementsByTagName(t).length > 0) ? this.getElementsByTagName(t) : false;
}
Secondly the easiest way to both read and write data to any element is to use textContent.
Read the fourth td on the third tr:
//Read an element's text node:
console.log(tag_('tr')[2].tag_('td')[5].textContent);
//Write to an element's text node:
tag_('table')[0].tag_('tr')[2].tag_('td')[5].textContent = '1,234');
JavaScript is a bit strict when it comes to types. So if you need to do some math with text content that you just read you need to convert it:
Number(tag_('tr')[1].tag_('td')[5].textContent);//'123' becomes `123`
Number(tag_('tr')[2].tag_('td')[2].textContent);//'a123' becomes `NaN` (Not a Number)
If I recall correctly I recently used the following to strip non-numeric text from a string:
var my_number = Number('String or replace with object reference'.replace(/\D/g,''));
Now that you're getting the read/write aspects and overcoming some of the more oddities associated with it I'll iterate over...iteration! You may already know this though I'm presuming a full answer is more desirable than a partial answer for not just you though also others reading this in the future.
var table = tag_('table');
for (var i = 0; i < table.length; i++)
{
console.log(table[i]);
var tr = table[i].tag_('tr');//Whatever table[i] is and it's table rows.
for (var j = 0; j < tr[i].length; j++)
{
console.log(tr[j]);
var td = table[i].tag_('tr')[j].tag_('td');//All the table data elements.
for (var k = 0; k < td.length; k++)
{
//apply read/write conditions here.
//potentially call a second global function to keep your code reusable.
}
}
}
That should help you get far enough with specific and iteral targeting of table data elements to help you learn and achieve your goals.
This is my first attempt in Javascript, so may be this is fairly easy question.
I need to access row element of a table, each row contains checkbox and two other column. If checkbox is checked, i need to get the id of checkbox.
I made following attempt but element_table.rows returns undefined, therefore i could not proceed. I debugged using Inspect element tool of eclipse and found element_table contains the rows.
Please suggest where I am making a mistake.
Javascript code:
function myfunction3(){
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table.rows;
var selectedTr = new Array();
var data = "";
for(var i =0 ; element_tableRows.length;i++)
{
var checkerbox = element_tableRows[i].getElementsByName('checkmark');
if(checkerbox.checked){
selectedTr[selectedTr.length] = element_tableRows[i].getAttribute("name");
data = data + element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
}
html code:
<table name="collection" border="1px">
<tr name="1">
<td><input type="checkbox" name="checkmark"></td>
<td>Tum hi ho</td>
<td>Arjit singh</td>
</tr>
<tr name="2">
<td><input type="checkbox" name="checkmark"></td>
<td>Manjha</td>
<td>Somesh</td>
</tr>
<tr name="3">
<td><input type="checkbox" name="checkmark"></td>
<td>Ranjhana</td>
<td>A.R Rehman</td>
</tr>
</table>
<input type="button" value="Check" onclick="myfunction3()">
here's a working version
function myfunction3(){
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table[0].rows;
var selectedTr = new Array();
var data = "";
for(var i =0 ; i < element_tableRows.length;i++)
{
var checkerbox = element_tableRows[i].cells[0].firstChild;
if(checkerbox.checked){
//selectedTr[selectedTr.length] = element_tableRows[i].getAttribute("name"); //not sure what you want with this
data = data + element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
alert(data);
}
http://jsfiddle.net/eZmwy/
jsfiddle for your example, your problem is mainly at when you getElementsByName you need to specify the index, also not that not all getElement methods are available in the table
i would also suggest you learn jQuery, this makes life easier, also not sure why you want to display the data as 1,2,3 the name on the tr... seems pretty strange to me
Actually this line
var element_table = document.getElementsByName('collection');
will return collection of elements. If you are sure that you have exactly one table with the specified name, try this approach:
var element_table = document.getElementsByName('collection')[0];
actually if you are using jQuery (very recommanded )
you can do something like
var idsArray = [];
$("[name=collection] tr td [type=checkbox]:checked").parent().each(function() {
idsArray .push($(this).attr('name'))
});
this answer related only to jQuery use (which is same as javascript only more compiled.)
Hello I have a piece of code that allows me to add an author.
I have a problem, I can't seem to delete the created node in my table
This is the worst frustration in my life. I could not seem to delete it.
I also have notice that every time I inspected the element I could not see the
new created element from the source. But when I view it on firebug I can actually see it there.
Adding an input element and appending it on the table works fine for me.
I am just very new to JavaScript and to this web thingy and deleting a CREATED ELEMENT via .createElement is where I am stuck at.
here is my code
<script>
var ctr = 1;
function showTextBox()
{
// is the table row I wanted to add the element before
var target = document.getElementById('bef');
var tblr = document.createElement('tr');
var tbld1 = document.createElement('td');
var tbld2 = document.createElement('td');
var tblin = document.createElement('input');
tblin.name = 'Author' + ctr;
tblin.id = 'Author' + ctr;
tblin.placeholder = 'add another author';
tbld1.appendChild( document.createTextNode('Author' + ctr ) );
tbld2.appendChild( tblin );
tblr.appendChild( tbld1 );
tblr.appendChild( tbld2 );
target.parentNode.insertBefore( tblr , target );
ctr++;
}
function hideTextBox()
{
var name = 'Author'+ctr;
var pTarget = document.getElementById('tbhold');
var cTarget = document.getElementById( name );
alert( cTarget ); // this one return null? Why? I have created id="Author1"
// viewing this code on source make the created elem to not appear
}
</script>
Am I doing something wrong? I really need help. This is for my project at school.
Is there any way I could delete it. I created that node and I want it to be deleted when I click something.
Also I prefer to stay with JS not with JQuery or other JStuff and I am disregarding compatibility for now because this is just a sample in my dummy form. I will deal on that later.
EDIT
In case you need the actual form here it is
<form enctype="multipart/form-data" action="process/" method="POST" />
<h3>Book Upload</h3>
<table border="2" id='tbhold'>
<tr>
<td>Title</td>
<td><input type="text" id="book_title" name="book_title" /></td>
</tr>
<tr>
<td>Author</td>
<td><input type="text" id="book_author" name="book_author" /></td>
</tr>
<tr id="bef">
<td colspan="2">
add author
remove
</td>
</tr>
</table>
</form>
Thank you very much!
Try this function:
function removeElements(elements){
for(var i = 0; i < elements.length; i++){
elements[i].parentNode.removeChild(elements[i]);
}
}
Then you can do this:
removeElements(document.querySelectorAll('#tbhold tr'));
function hideTextBox(){
var name = "Author" + (ctr - 1);
var pTarget = document.getElementById('tbhold');
var cTarget = document.getElementById(name);
var tr = cTarget.parentNode.parentNode;
tr.parentNode.removeChild(tr);
ctr = ctr - 1;
}
Here is a demo
every time I inspected the element I could not see the new created element from the source. But when I view it on firebug I can actually see it there.
If you change the DOM, you of course do not change the HTML source markup. Only the DOM inspector will show you the changes.
var name = 'Author'+ctr;
var cTarget = document.getElementById( name );
alert( cTarget ); // this one return null? Why? I have created id="Author1"
Yes, you created it using your showTextBox function. But that did also increment the ctr to 2, so that you now are looking for Author2 which obviously does not exist. So put a ctr--; before it and it should work.