Change style of table cells on click - javascript

I want to change the color of specific table cells when clicking a button.
<button onclick="highlight()">Toggle highlighting</button>
And JS:
function highlight() {
var x = document.getElementsByClassName('best');
for (var i = 0; i < x.length; i++) {
x.get(i).style.color = "green";
}
}
I added the table cells I want to change to the class "best", but when clicking the button, nothing changes. I first tried to assign them all to a single ID and use document.getElementById('best').style.color = "green";, but this only changed the first element that had the id "best" and not all. How should highlight() look like?

You don't need to use x.get(i) there. Just access the element using x[i]
See the following code:
function highlight() {
var x = document.getElementsByClassName('best');
for (var i = 0; i < x.length; i++) {
x[i].style.color = "green";
}
}

First off, I'd recommend using Javascript's built in forEach() function when working with a nodeList like this as there is less chance of an off by one error:
bestElements.forEach(best => {
best.style.color = "green";
});
Second, I believe you may be looking for the background-color attribute, not the color attribute if you are trying to change the color of the entire cell.
bestElements.forEach(best => {
best.style.backgroundColor = "green";
});

Related

How to clear previous content from a table cell

I'm trying to add a "clearing" function to my table that calculates totals. So that when person first time presses button that does the calculation, then changes amounts of products and then presses again, the previous answer would be cleared and new added.
I have tried like this:
function clear () {
var table = document.getElementById("pricetable");
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
rows[i].className = "";
var cells = rows[i].getElementsByTagName("td");
for (var j = 1; j < cells.length - 1; j++) {
cells[j].className = "";
}
}
}
Then I'm calling the function in the beginning of my previous function that calculates the amounts and prices:
function calculate () {
clear ();
...
}
But nothing happens. I was thinking that it might have something to do with the fact that I have created the last row and also the last column (which both include the totals) dynamically. The id of the row is lastRow, and the column doesn't have id.
And I don't want to use jquery or add classes, ids etc to the html file. So does anyone know what's wrong with my code?
className just clears styling.
You're looking for innerHTML:
...
for (var j = 1; j < cells.length - 1; j++) {
cells[j].innerHTML = "";
}
...
className refers to the CSS class name(s) applied to an element. Here's what your current code does:
Before
<td class='foo'>999</td>
After
<td class=''>999</td>
innerHTML pretty much does what it says:
Before
<td class='foo'>999</td>
After
<td class='foo'></td>
Also, I just noticed your for loop starts at 1. Hopefully this was intentional ;)
I can see that you are setting the className to nothing rather than setting the innerHTML to nothing...
Try replacing this:
cells[j].className = "";
With this:
cells[j].innerHTML = "";

Change Colors (onclick) using Javascript

I was coding a website and was trying to change a few colors and pictures onclick using JavaScript to change the CSS. However this code is only partially working. Only the "txtArea" field changes color. Checked the validators and consoles its perfect syntax.??
<!-- This is the button to change the color, Its 1 bulletin point. -->
<div id="colorSelector"><span id="chngBlue">•</span> • •</div>
<script>
var colors = ["#0099cc", "#669900", "#993333"];//Blue, Green, Red
function chngColor(){
document.getElementById("txtArea").style.backgroundColor = colors[2];
document.getElementsByClassName("labHdr").style.backgroundColor = colors[2];
document.getElementById("newLink").style.color = colors[2];
document.getElementById("hdBanner").src='bannerred.png';
}
</script>
document.getElementsByClassName("labHdr") return a HTMLCollection (Thanks #Teemu for the clarification), so it haven't 'style'. You can do something like
var myElements = document.getElementsByClassName("labHdr");
for (var i = 0; i < myElements.length; i++) {
myElements[i].style.color = colors[2];
}
getElementsByClassName returns an array-like object, so you need to index into this array even if it only contains one element.
So the second line of the function becomes:
document.getElementsByClassName("labHdr")[0].style.backgroundColor = colors[2];
http://codepen.io/markwill/pen/rrAXzr
If there is more than one element with this class you'll need to iterate over all of them setting the style (this is safer than just assuming that there's just one).
Replace:
function chngColor(){
document.getElementById("txtArea").style.backgroundColor = colors[2];
document.getElementsByClassName("labHdr").style.backgroundColor = colors[2];
document.getElementById("newLink").style.color = colors[2];
document.getElementById("hdBanner").src='bannerred.png';
}
By that:
function chngColor(){
var labelList = document.querySelectorAll(".labHdr");
document.getElementById("txtArea").style.backgroundColor = colors[2];
document.getElementById("newLink").style.color = colors[2];
document.getElementById("hdBanner").src='bannerred.png';
Array.prototype.map.call(labelList, function(element) {
element.style.backgroundColor = colors[2];
});
}
With this all your labels will be change.
You can simply get element by id for change color below example which get more idea
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>

unable to change colors of a tag

i have this code
Click Me
Click Me 2
And then the Js
var mainLinker = document.getElementsByTagName('a');
for (var i = 0; i < mainLinker.length; i++) {
this.style.color = 'red';
}
But i get this error
Cannot set property 'color' of undefined
Please tell me where am i doing it wrong.
this is not what you want.
Change the loop body to
mainLinker[i].style.color = 'red';
or equivalently use forEach (edited with #Vohuman's comment):
[].forEach.call(document.getElementsByTagName('a'), function(el) {
el.style.color = 'red';
});
You refer to this in an object
Your function is not in an object
This will work
var mainLinker = document.getElementsByTagName('a');
for (var i = 0; i < mainLinker.length; i++) {
mainLinker[i].style.color = 'red';
}
Of course your basic problem is using this, as pointed out in other answers. But why are you doing this instead of using a CSS rule such as
a { color: red; }
If you want to make this conditional somehow, then add a class at a higher level, such as body, to control it:
body.make-links-red a { color: red }
Then, when you want to make links red, do
document.body.classList.add('make-links-red')

JavaScript: get custom button's text value

I have a button that is defined as follows :
<button type="button" id="ext-gen26" class=" x-btn-text">button text here</button>
And I'm trying to grab it based on the text value. Hhowever, none of its attributes contain the text value. It's generated in a pretty custom way by the look of it.
Does anyone know of a way to find this value programmatically, besides just going through the HTML text? Other than attributes?
Forgot one other thing, the id for this button changes regularly and using jQuery to grab it results in breaking the page for some reason. If you need any background on why I need this, let me know.
This is the JavaScript I am trying to grab it with:
var all = document.getElementsByTagName('*');
for (var i=0, max=all.length; i < max; i++)
{
var elem = all[i];
if(elem.getAttribute("id") == 'ext-gen26'){
if(elem.attributes != null){
for (var x = 0; x < elem.attributes.length; x++) {
var attrib = elem.attributes[x];
alert(attrib.name + " = " + attrib.value);
}
}
}
};
It only comes back with the three attributes that are defined in the code.
innerHTML, text, and textContent - all come back as null.
You can do that through the textContent/innerText properties (browser-dependant). Here's an example that will work no matter which property the browser uses:
var elem = document.getElementById('ext-gen26');
var txt = elem.textContent || elem.innerText;
alert(txt);
http://jsfiddle.net/ThiefMaster/EcMRT/
You could also do it using jQuery:
alert($('#ext-gen26').text());
If you're trying to locate the button entirely by its text content, I'd grab a list of all buttons and loop through them to find this one:
function findButtonbyTextContent(text) {
var buttons = document.querySelectorAll('button');
for (var i=0, l=buttons.length; i<l; i++) {
if (buttons[i].firstChild.nodeValue == text)
return buttons[i];
}
}
Of course, if the content of this button changes even a little your code will need to be updated.
One liner for finding a button based on it's text.
const findButtonByText = text =>
[...document.querySelectorAll('button')]
.find(btn => btn.textContent.includes(text))

How to change the color of the links with javascript?

I want to know how can I manipulate all the links on a page with javascript. I can get elements by id's with document.getElementById(id), but how can I get the links? And also how can I get all elements with a certain classname? I want to change the color of the link and class elements.
I mean these links:
This is a link
And an example for an element with a class:
<span class="link">This is an element with a class</span>
Please no jquery. I want javascript.
Simple and straightforward (in pure JS too!)
colorLinks("#00FF00");
function colorLinks(hex)
{
var links = document.getElementsByTagName("a");
for(var i=0;i<links.length;i++)
{
if(links[i].href)
{
links[i].style.color = hex;
}
}
}
If it's a class name you're looking for and you know the tag, just use this.
var elements = document.getElementsByTagName("span");
for(var j=0;j<elements.length;j++)
{
if(elements[j].className === "your class here")
{
//do something
}
}
You can also look at getElementsByClassName and querySelectorAll. Both have support in most new browsers.
The pure-JavaScript version isn't all that complicated:
var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++) {
if (elements.className.split(/\s+/).indexOf('red') !== -1) {
elements[i].style.color = 'red';
}
}
And for modern browsers:
var elements = document.querySelectorAll('a.red');
[].slice.call(elements).forEach(function(elem) {
elem.style.color = 'red';
});
Update: I still recommend using jQuery, but, if you want to learn how to do it without, I would recommend heading over to this site. This shows how to change link colors when you mouse over the link, but you can easily extrapolate for your specific situation: Javascript Change Link Text Color onmouseover
--
Ottomanlast has a good point about checking out jQuery to help you out with this task (although it can be done without the use of a library). However, just so you have an example of what he is talking about, here is how you could change link colors using jQuery.
$('.linkClass').click(function(){
$(this).css('color', 'green');
});
This example changes the color of a specific link when it is clicked.
$('a').css('color', 'green');
This example will change all the links to a green color.
$('.linkClass').click(function(){
$(this).removeClass('oldClass');
$(this).addClass('newClass');
});
This does the same thing as the first example, but this removes and adds CSS classes that you already have defined elsewhere. (I would recommend this method over just editing the CSS directly.)
Anyway, the point I'm trying to make is that jQuery makes it extremely easy to select and then make changes to the objects within your HTML document. You may want to take a look into it.
You can use document.getElementsByTagName("a"). This function returns an array of the <a> elements in the page. Loop over this array, and use .style.color = "#000000" in each element.
This is how I change all hyperlink colors (normal/hover):
function changeTextHyperlinkColours(inputColorNormal, inputColorHover) {
var sheets = document.styleSheets;
var slen = sheets.length;
for(var i=0; i<slen; i++) {
var rules = document.styleSheets[i].cssRules;
var rlen = rules.length;
for(var j=0; j<rlen; j++) {
if (rules[j].selectorText == 'a') {
rules[j].style['color'] = inputColorNormal;
}
if (rules[j].selectorText == 'a:hover') {
rules[j].style['color'] = inputColorHover;}
}
}
}
}
Also you can embed the link text in the span and change the color
<a href='www.mydomain.com'><span onclick='this.style.color="red"'>Visit Us</span></a>

Categories