I'm trying to create a webpage where there are three working buttons that are labelled "Red", "Green", and "Blue". When the user clicks on one of the buttons, the entire webpage should change to the color of the specific button that was clicked.
This is what I have so far, but I'm pretty sure I'm doing something wrong:
function myFunction() {
document.getElementById("H1").style.color = "#ff0000";
}
<h1 id="H1">H1</h1>
<button type="button" onclick="myFunction()">Set H1 to Red</button>
We begin with creating three radio buttons named red, green, blue inside the form tag and use attribute named on Click and assign value document. bgcolor=color name to it.
There is only one problem here that you changed color but you want to change background color.
Hope this will help you.
function myFunction() {
document.body.style.backgroundColor = "#ff0000";
}
onClick the button will invoke the changeColor function which will take the innerText
of the button as style value and set it as background color of the body.
function changeColor (element){
document.body.style.backgroundColor = element.innerText
}
console.log(document.body.style.backgroundColor)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="changeColor(this)" >Red</button>
<button onclick="changeColor(this)" >Green</button>
<button onclick="changeColor(this)" >Blue</button>
</body>
</html>
You can also use class or id selector to select the element instead of using tag name.
const element = document.getElementsByClassName(".class")
In this case the element will be an array of nodes that have the same class. You can use forEach loop to trigger color change on all of them.
or use an Id if the target is a single element.
const element = document.getElementById("id")
You can also use onclick event listener to change the color.
First the "problems," which I'm not convinced are problems since clicking the <button> does exactly what the <button> says – in its text – that it will do. However:
function myFunction() {
// as the button-text implies this JavaScript retrieves
// the element with the id of 'H1', and updates its
// CSS - via the inline style element - to the colour
// of '#ff0000' (or '#f00'), which is red.
document.getElementById("H1").style.color = "#ff0000";
}
<h1 id="H1">H1</h1>
<!-- Obviously you know that this element is intended to set
the colour of the <h1> element, given the text of the
<button>; also you're using an inline event-handler
(the 'onclick' attribute) to bind a function to an event,
which is considered bad practice due to the obtrusive
nature of the event-binding, and difficulty of updating
function calls: -->
<button type="button" onclick="myFunction()">Set H1 to Red</button>
To do as you ask, and instead set the background-color of a given element, we must:
retrieve that element in the JavaScript,
update the correct – background-color – property,
find a means by which the <button> can "communicate" the correct value to which that property must be set, and ideally
use unobtrusive JavaScript to bind the function to the 'click' event.
To do that:
// assigning a meaningful name to the function
// in order to make future maintenance easier:
function setBackgroundColor(evt) {
// retrieving the element we wish to style:
const body = document.querySelector('body')
// accessing the style interface, and
// updating the background-color, via the
// JavaScript camelCased property-name:
body.style.backgroundColor = evt.currentTarget.value;
}
// retrieving the <button> elements:
const buttons = document.querySelectorAll('button');
// iterating over that NodeList of <button>
// elements, using NodeList.prototype.forEach():
buttons.forEach(
// using an Arrow function, passing in a reference
// to the current Node of the NodeList over which
// we're iterating. Here we use the
// EventTarget.addEventListener() method to bind the
// setBackgroundColor() functiona as the 'click'
// event-handler when the node is clicked (also fired
// on keyboard navigation if the user hits spacebar
// or enter):
(node) => node.addEventListener('click', setBackgroundColor)
)
<h1 id="H1">H1</h1>
<!-- here we're adding a "value" attribute to hold
the colour to set; we're using a colour-name
('red'), a hexadecimal ('#87cefa'), and
a hsl() ('120deg 93% 80%') value as the colour: -->
<button type="button" value="red">Red</button>
<button type="button" value="#87cefa">Blue</button>
<button type="button" value="hsl(120deg 93% 80%)">Red</button>
There is, of course, an alternative and that's to use a colour-picker <input>, which allows the user to pick any colour of their choice and simply pass the chosen value to the function:
// assigning a meaningful name to the function
// in order to make future maintenance easier:
function setBackgroundColor(chosenColor) {
// caching the <body> element:
const body = document.querySelector('body');
// updating the background-color via the
// 'style' interface:
body.style.backgroundColor = chosenColor;
}
// retrieving the <input> element with a type-attribute
// equal to "color":
const input = document.querySelector('input[type=color]');
// using EventTarget.addEventListener() to use the anonymous
// function to call the setBackgroundColor() function, passing
// the value of the evt.currentTarget node (the color <input>)
// as the argument:
input.addEventListener('change', (evt)=> setBackgroundColor(evt.currentTarget.value));
<h1 id="H1">H1</h1>
<input type="color">
References:
Arrow functions.
CSSStyleDeclaration.
document.querySelector().
document.querySelectorAll().
EventTarget.addEventListener().
I am new to jquery and was wondering how I can point one html element equal to another. I want to make it so that whenever something in the h2 tag changes, the text within the p tags will copy the change. Below is how my tags are set up within the class fc-center.
var title = $('div.fc-center h2').text();
$('.fc-center').append('<p>'+'' +'</p>');
with the html looking something like
<div class = 'fc-center'>
<h2> text text</h2>
<p> </p>
</div>
essentially what I want to do is something like this :
$('div.fc-center p').equalto $('div.fc-center h2')
But I am not quite sure how to go about it
I propose this solution:
var title = $('.fc-center').find('h2').text();
var elementsP=$('.fc-center').find('p');
if (elementsP.length > 0) {
$.each(elementsP, function(i, val) {
$(this).empty().html(title);
});
}
https://jsfiddle.net/julian9319/grc0y6qf/1/
I have been trying to print after modifying html element but element has not been changed. (Angular2)
This source code is simplified one.
<div *ngIf="displayType === 'screen'">
<div>This is Screen</div>
</div>
<div *ngIf="displayType === 'print'">
<div>This is Print</div>
</div>
And when click a button the following event.
displayType: string = 'screen'; // default
OnPrint() {
this.displayType = 'print';
let tmp = document.createElement('div');
let el = this.elementRef.nativeElement.cloneNode(true);
tmp.appendChild(el);
let content = tmp.innerHTML;
let frame1 = document.createElement('iframe');
document.body.appendChild(frame1);
let frameDoc = frame1.contentWindow;
frameDoc.document.open();
frameDoc.document.write('<html><body>'+content+'</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
document.body.removeChild(frame1);
}, 500);
}
But contents are elements before modifying.
How can I refresh elements?
To refresh the elements you need to trigger the change detection.
Here is a very good post about change detection in Angular 2: http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html
I've created a plunker here to illustrate it:
http://plnkr.co/edit/0ZwkaQ776mKpLYZJogYx?p=preview
<button (click)="OnPrint()">OnPrint</button>
Also you should not modify the DOM elements directly, you should create a component and use a structural directive to display it (here the component has a selector "my-print"):
<my-print *ngIf="isPrint" [iframeSrc]="..."></my-print>
I'm using a script to do a mouseover effect with images and also highlighting text in a different color using the getElementById phrase. I understand that an ID can only be used once, and if it needs to be used more than once I should use class. But there is no getElementByClass function. I have 2 areas of type that I want to highlight, one is centered, the other is left justified. Is there a way to use the same id for both styles?
<div id="georgia">
<style="text-align: center;">
<strong>Headquarters:
</strong>
</style>more text here
</div>
This is the script I am using:
<script type="text/javascript">// < ![CDATA[
function on(el) {
if (document.getElementById(el)) {
document.getElementById(el).style.color="green";
};
};
function off(el) {
if (document.getElementById(el)) {
document.getElementById(el).style.color="";
};
};
// ]]></script>
So what you are saying is I can replace the getElementById with getElementByClassName then it will work?
This is the format I'm using, the first part of the text (Headquarters) is not showing up, but the second part (more text here) is fine.
You need to use document.getElementsByClassName, which returns a list of the objects with that class name:
var all = document.getElementsByClassName("bar");
for(var i = 0; i < all.length; i++){
var obj = all[i];
obj.style.fontWeight = 'bold';
}
<div id="foo" class="bar">hi</div>
<div class="bar">bye</div>
<div id="bar">sup</div>
Consider this sample code-
<div>
<outer-tag> Some Text <inner-tag> Some more text</inner-tag></outer-tag>
</div>
I want to get the following output -
<div>
<inner-tag> Some more text</inner-tag>
</div>
How do I achieve this? Thanks!
This solution will work for your current example:
String html = "<div>"
+ "<outer-tag> Some Text <inner-tag> Some more text</inner-tag></outer-tag>"
+ "</div>";
Document doc = Jsoup.parseBodyFragment(html);
for (Element _div : doc.select("div")) {
// get the unwanted outer-tag
Element outerTag = _div.select("outer-tag").first();
// delete any TextNodes that are within outer-tag
for (Node child : outerTag.childNodes()) {
if (child instanceof TextNode) child.remove();
}
// unwrap to remove outer-tag and move inner-tag to child of parent div
outerTag.unwrap();
// print the result
System.out.println(_div);
}
Result is:
<div>
<inner-tag>
Some more text
</inner-tag>
</div>