Change a selected id's class when on click JavaScript - javascript

I'm looking for a method of changing the class of a selected id. I aim to do this with java but I can't seem to work out how. So in my example I have 4 "p" tags each with a different id and all with the class "na" now what I want to do is when one of the "p" tags is click it swaps the class to "under" and resulting in the tag being underlined. Can anyone point me in the right direction here to simplify it?
EDIT
Sorry guys, I forgot to add the JavaScript.
function class1() {
document.getElementById("p1").className = "under";
document.getElementById("p2").className = "na";
document.getElementById("p3").className = "na";
document.getElementById("p4").className = "na";
}
function class2() {
document.getElementById("p1").className = "na";
document.getElementById("p2").className = "under";
document.getElementById("p3").className = "na";
document.getElementById("p4").className = "na";
}
function class3() {
document.getElementById("p1").className = "na";
document.getElementById("p2").className = "na";
document.getElementById("p3").className = "under";
document.getElementById("p4").className = "na";
}
function class4() {
document.getElementById("p1").className = "na";
document.getElementById("p2").className = "na";
document.getElementById("p3").className = "na";
document.getElementById("p4").className = "under";
}
.under {
font-size: 16px;
font-weight: bold;
text-decoration: underline;
}
.na {
font-size: 16px;
font-weight: bold;
}
<p id="p1" class="na" onclick="class1()">Para1</p>
<p id="p2" class="na" onclick="class2()">Para2</p>
<p id="p3" class="na" onclick="class3()">Para3</p>
<p id="p4" class="na" onclick="class4()">Para4</p>

It looks like you over-complicated the task.
Using jQuery, this is super simple to achieve in only one "two lines" function.
$(".na").on("click", function(){
// Remove the class under from all p element.
$(".na").removeClass("under");
// Add the class under to the one clicked.
$(this).addClass("under");
});
.under {
text-decoration: underline;
}
.na {
font-size: 16px;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="p1" class="na">Para1</p>
<p id="p2" class="na">Para2</p>
<p id="p3" class="na">Para3</p>
<p id="p4" class="na">Para4</p>

Related

cuatomize radio input with "fonts.googleapis"

Good morning. Improving this code I found it difficult to insert a custom radio with fonts.googleapis to show after the quiz verification function. Something like the attached image Do you have any suggestions? or better yet an example of code.... heartfelt thanks to the community, I wish you a good day to all and happy coding
var answers = ["1b"];
var rads, quiz; // need to be set after load
window.addEventListener("load",function() { // when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document.getElementById("scoreButton").addEventListener("click",function(e) { // on click of scoreme
var score = 0;
for (var i=0;i<rads.length;i++) { // loop over all radios in the form
var rad = rads[i];
var idx = rad.name.substring(1)-1; //remove the q from the name - JS arrays start at 0
var checked = rad.checked;
var correct = rad.value==answers[idx];
if (correct) {
rad.closest("label").classList.toggle("correct");
}
else if (checked) {
rad.closest("label").classList.toggle("error")
}
}
});
});
.correct {
color: green;
font-weight: bold;
text-decoration: underline;
border-left: 2px solid green;
}
.error {
color: red;
font-weight: bold;
text-decoration: line-through;
border-left: 2px solid red;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<form id="quiz">
<div class="questions">
<dl id="1">
<dd><b>1. QUESTION.</b><br>
<label><input type="radio" name="q1" value="1a"> 1. WRONG</label><br>
<label><input type="radio" name="q1" value="1b"> 2. RIGHT</label><br>
<label><input type="radio" name="q1" value="1c"> 3. WRONG</label>
</dd>
</dl>
<input type="button" value="RESULT" id="scoreButton">
</div>
</form>
var answers = ["1b", "1c"];
var rads, quiz, cur, par;// need to be set after load
var ShowAnswer = true; // Try false
window.addEventListener("load", function() {
// when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document
.getElementById("scoreButton")
.addEventListener("click", function(e) {
// on click of scoreme
cur = quiz.querySelector("input[type=radio]:checked");
par = cur.parentNode;
var score = 0;
for (var i = 0; i < rads.length; i++) {
// loop over all radios in the form
var rad = rads[i];
var idx = rad.name.substring(1) - 1; //remove the q from the name - JS arrays start at 0
var checked = rad.checked;
var correct = !(answers.indexOf(cur.getAttribute("value")) == -1);
rad.style.appearance = 'none';
document.getElementById("scoreButton").style.display = 'none';
if (!(answers.indexOf(rad.getAttribute('value')) == -1) && ShowAnswer) {
rad.parentNode.classList.add("correct");
rad.parentNode.innerHTML =
`<span class="material-icons-round correct c">check</span>` +
rad.parentNode.innerHTML;
}
if (correct) {
par.classList.add("correct");
par.innerHTML =
`<span class="material-icons-round correct c">check</span>` +
par.innerHTML;
} else if (checked) {
par.classList.add("error");
par.innerHTML =
`<span class="material-icons-round error e">close</span>` +
par.innerHTML;
}
}
});
});
.correct {
color: green;
font-weight: bold;
text-decoration: underline;
}
.c {
text-decoration: none;
border-left: 0px;
margin-left: -24px;
/*From https://fonts.googleapis.com/icon?family=Material+Icons+Round*/
}
.error {
color: red;
font-weight: bold;
text-decoration: line-through;
}
.e {
text-decoration: none;
border-left: 0px;
margin-left: -24px;
/*From https://fonts.googleapis.com/icon?family=Material+Icons+Round*/
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons+Round" rel="stylesheet">
<form id="quiz">
<div class="questions">
<dl id="1">
<dd><b>1. QUESTION.</b><br>
<label><input type="radio" name="q1" value="1a"> 1. WRONG</label><br>
<label><input type="radio" name="q1" value="1b"> 2. RIGHT</label><br>
<label><input type="radio" name="q1" value="1c"> 3. WRONG But shown as right due to value in js</label>
</dd>
</dl>
<input type="button" value="RESULT" id="scoreButton">
</div>
</form>
Here is a PEN
Edited with replacement of choose option hiding!

How to change an id of a span tag using query?

I have a program where everything works except one line. The code is to apply the class "footerStyle" to the span id named "footer1". When working correctly the line in footer1 should increase in size and change font family's.
Code must use querySelector or querySelectorAll
Full code, but code in question is labeled.
LOCATION - THIRD LINE FROM END
<style>
/*class names always begin with a . */
.ImportantStuff {
color: red;
font-family: Britannic;
font-size: xx-large;
text-align: center;
}
.SortOfImportantStuff {
color: green;
font-family: Calibri;
font-size: x-large;
text-align: center;
}
/*ids always begin with a # */
/*it will look for all elements with id of ChangeButton*/
#ChangeButton {
background-color:orange;
}
/*for the style below: since there is no # or . - it will look for an HTML element*/
/*so all div tags will follow this style*/
div {
color: blue;
font-family: cursive;
font-size: medium;
}
.footerStyle{
font-family:'Lucida Sans';
font-size: x-large;
}
</style>
</head>
<body>
<!--all the attributes of an object appear in red:-->
<input id="ChangeButton" type="button" value="Change the look of this page." onclick="ChangeThis()" />
<h1 class="ImportantStuff">Here we go - let's have some fun.</h1>
<p>In case you'd rather be on some much funner web sites:</p>
<br />
<!--target = "_blank" makes the page open in a new window or tab-->
Cedar Point
<br />
Face Book
<br />
YouTube
<br />
<div>
<b>Places I'd like to visit:</b>
<div>
Alaska
<img src="Images/Alaska.jpg" />
</div>
<div>
Australia
<img src="Images/Australia.jpg" />
</div>
<div>
Maine
<img src="Images/Maine.jpg" />
</div>
</div>
<span id="footer1">Maybe someday I'll get to these places.</span>
<br />
<span id="footer2">Until then, I'll just save my money.</span>
<script>
function ChangeThis() {
var allas = document.querySelectorAll("a");
for (x = 0; x < allas.length; x++) {
allas[x].setAttribute("class", "SortOfImportantStuff");
}
document.querySelector("p").style.color = "red";
document.querySelector("p").style.backgroundColor = "green";
var allimgs = document.querySelectorAll("img");
for (x = 0; x < allimgs.length; x++) {
allimgs[x].style.width = 250 + 'px';
allimgs[x].style.height = 150 + 'px';
}
var InnerDivs = document.querySelectorAll("div div");
for (x = 0; x < InnerDivs.length; x++) {
InnerDivs[x].style.color = "red";
}
//CODE IN QUESTION
document.querySelector("#footer1", ".footerStyle");
//
document.querySelector('#footer2').textContent = 'Happy Halloween';
}
</script>
Answer:
document.querySelector('#footer1').setAttribute("class", "footerStyle");

CSS Not Applied to Node Added by JS appendChild

My html:
<div id=Info>
<p>Id: <span>001</span></p>
</div>
My CSS:
#Info p {
font-weight: bold;
}
#Info span {
font-weight: normal;
}
My JS code:
var pElement = document.createElement('p');
var spanElement = document.createElement("span");
var elementValue1 = document.createTextNode("Id: ");
var elementValue2 = document.createTextNode("003");
spanElement.appendChild(elementValue1);
pElement.appendChild(elementValue2);
pElement.appendChild(spanElement);
document.querySelector('#Info').appendChild(pElement);
CSS style applied correctly to the line:<p>Id: <span>001</span></p> from html file. But somehow, CSS style is not applied to the node added by appendChild from JS file. I couldn't figure out why.
I'm new to html/CSS/JS, any help would be appreciated!
Thanks!
It looks like the div id is not match between your html and the css.
In the html, the id=Info should be id="bookInfo"
Is seems to be qworking perfectly fine, but there are multiple issues in shared code.
CSS is referring to #bookInfo as opposed to #Info
You are appending elementValue1 to spanElement as opposed to elementValue2.
Let's look at fixed code:
var pElement = document.createElement('p');
var spanElement = document.createElement("span");
var elementValue1 = document.createTextNode("Id: ");
var elementValue2 = document.createTextNode("003");
spanElement.appendChild(elementValue2);
pElement.appendChild(elementValue1);
pElement.appendChild(spanElement);
document.querySelector('#Info').appendChild(pElement);
#Info p {
font-weight: bold;
}
#Info span {
font-weight: normal;
}
<div id=Info>
<p>Id: <span>001</span></p>
</div>
not a good way to do it but here is your code:
https://jsfiddle.net/r6j31zhL/
<html>
<body>
<div id="Info">
<p>Id: <span>001</span></p>
</div>
</body>
</html>
<style>
#Info p {
font-weight: bold;
}
#Info span {
font-weight: normal;
}
</style>
<script>
var pElement = document.createElement('p');
var spanElement = document.createElement("span");
var elementValue1 = document.createTextNode("Id: ");
var elementValue2 = document.createTextNode("003");
spanElement.appendChild(elementValue2);
pElement.appendChild(elementValue1);
pElement.appendChild(spanElement);
document.querySelector('#Info span').appendChild(pElement);
</script>

How do I check if a letter is bold?

I'm trying to change all bold characters to italic ones and vica versa. I figured out I need to iterate through the entire document.
So far I defined the two styles and a part of the function, not sure if the styles are needed.
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
<script>
function swap() {
if (fontWeight == 'bold') {
fontWeight == 'normal';
fontStyle == 'italic';
}
elseif (fontStyle == 'italic') {
fontStyle == 'normal';
fontWeight == 'bold';
}
</script>
Well, you could do this with querySelectorAll, considering only swapping .bold and .italic depending on their current class:
function swapCollection( collection, from, to ) {
if ( !collection ) {
return;
}
for( let i = 0; i < collection.length; ++i ) {
const elm = collection[ i ];
elm.classList.remove( from );
elm.classList.add( to );
}
}
function swap() {
const allBold = document.querySelectorAll( '.bold' );
const allItalic = document.querySelectorAll( '.italic' );
swapCollection( allBold, 'bold', 'italic' );
swapCollection( allItalic, 'italic', 'bold' );
}
document.getElementById( 'swap' ).addEventListener( 'click', swap );
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
<div>
<span class="bold">Hello</span> <span class="italic">world!</span>
</div>
<button id="swap">swap</button>
You can also use getElementsByClassName to choose class and change style then:
function swap() {
var mass=document.getElementsByClassName("bold");
for (i in mass){
mass[i].style.fontWeight="normal";
}
}
it's not useful to add a JS script for something that can be done once and for all.
so try to overwrite the default style of strong and em tags inyour CSS files by adding the following CSS code
strong, b{ font-weight: normal!important; font-style: italic!important; }
em, i{font-style: normal!important; font-weight: bold!important; }
then replace all properties in your CSS files
font-style: italic; by font-weight: bold;
and
font-weight: bold; by font-style: italic;
using your IDE
This is a generalize solution, using jQuery, not based only on class names.
I do the bolded texts red so you can see it easily.
$('div').each(function () {
if ($(this).css('font-weight') == 'bold') {
$(this).css('color', 'red'); // but you change to italic
return;
}
if ($(this).css('font-style') == 'italic') {
$(this).css('color', 'green'); // but you change to bold
return;
}
});
.one, .three {font-weight: bold;}
.five {font-style: italic;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one">aaa</div>
<div>ccc</div>
<div class="three">ddd</div>
<div>eee</div>
<div style="font-weight: bold;">lala</div>
<div style="font-style: italic;">tata</div>
<div>nana</div>
<div class="five">dada</div>
If you want to apply something to a text which is both bold and italic, remove the returns in the if blocks.
If it is simply a matter of toggling the classes, you could do it like this. Each time you click the button it will change the bold text to italic and vice versa.
const
trigger = document.getElementById('trigger');
function toggleClasses() {
const
// Get all the elements with the bold and/or italic class.
elements = document.querySelectorAll('.bold, .italic');
// Iterate over all the elements
elements.forEach(element => {
// For each element, toggle the bold and italic classes.
element.classList.toggle('bold');
element.classList.toggle('italic');
});
}
trigger.addEventListener('click', toggleClasses);
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
<p class="bold">initally bold</p>
<p class="bold">initally bold</p>
<p class="italic">initally italic</p>
<p class="bold">initally bold</p>
<p class="italic">initially italic</p>
<button id="trigger" type="button">toggle classes</button>
You may simply collect all items with .bold and .italic classes under a node list with document.querySelectorAll(".bold, .italic") and toggle their classLists.
var sps = document.querySelectorAll(".bold, .italic"),
mbt = document.getElementById("mbt");
mbt.addEventListener("click", _ => sps.forEach(function(sp){
sp.classList.toggle("bold");
sp.classList.toggle("italic");
}));
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
<p><span class="bold">Hello</span> <span class="italic">World</span></p>
<button id="mbt">Toggle</button>

How to wrap div element around newly typed text so that associated css result will be shown in real time

I have created a simple text editor which shows the associated CSS results in real time. for example if a user clicks Bold Then text becomes bold while user is typing (it shows real time change). Same like this I want a button after click it will wrap the new text with a div tag with specified class or id.
I know wrap method can wrap the div or other tag. But after adding new div tags through wrap() I want store its result which contains newly added div tags. so that I can use those result to generate new html pages.
Here is the html code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script src="texteditor.js"></script>
</head>
<body>
<div id="content" style="margin-top: 10px; height: 70%; text-align: center;">
<h2><u>Simple Text Editor Created Using jQuery</u></h2>
<div class="ze ie"></div>
<style>
.font-bold.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
.selected {
background-color: orange;
}
#openpb {
margin: 15px;
}
</style>
<button type="button" class="g-button g-button-submit" id='stext'>Text</button>
<button type="button" class="g-button g-button-submit" id='shtml'>HTML</button>
<div id="controls" style="margin-bottom: 10px;">
<a id="bold" style="color: black; display: inline-block;" class="font-bold">
<button type="button">B</button>
</a>
<a id="italic" style="color: black !important; display: inline-block;" class="italic">
<button type="button">I</button>
</a>
<a id="link" class="link" style="display: inline-block;">
<button type="button">Link</button>
</a>
<select id="fonts" class="g-button">
<option value="Normal">Normal</option>
<option value="Arial">Arial</option>
<option value="Comic Sans MS">Comic Sans MS</option>
<option value="Courier New">Courier New</option>
<option value="Monotype Corsiva">Monotype</option>
<option value="Tahoma New">Tahoma</option>
<option value="Times">Times</option>
<option value="Trebuchet New">Trebuchet</option>
<option value="Ubuntu">Ubuntu</option>
</select>
</div>
<iframe frameborder="0" id="textEditor" style="width: 500px; height: 80px; border: 2px solid #CCC; border-radius: 20px; overflow: auto;"></iframe>
<textarea name="text" id='text' style="border-radius: 20px; overflow: auto; display: none; padding-left: 10px;" rows="6" cols="53"></textarea>
</div>
</body>
</html>
here is Jquery: as you can I have used setinterval method to show result in real time in textarea. same like this I want a button which will wrap new or selected text with div tag with specified id and class and I want store this changes(newly added div tag) in textarea.
$(document).ready(function () {
document.getElementById('textEditor').contentWindow.document.designMode = "on";
document.getElementById('textEditor').contentWindow.document.close();
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
$("#bold").click(function () {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
boldIt();
});
$("#italic").click(function () {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
ItalicIt();
});
$("#fonts").on('change', function () {
changeFont($("#fonts").val());
});
$("#link").click(function () {
var urlp = prompt("What is the link:", "http://");
url(urlp);
});
$("#stext").click(function () {
$("#text").hide();
$("#textEditor").show();
$("#controls").show()
});
$("#shtml").on('click', function () {
$("#text").css("display", "block");
$("#textEditor").hide();
$("#controls").hide();
});
});
function boldIt() {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("bold", false, "");
edit.focus();
}
function ItalicIt() {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("italic", false, "");
edit.focus();
}
function changeFont(font) {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("FontName", false, font);
edit.focus();
}
function url(url) {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("Createlink", false, url);
edit.focus();
}
setInterval(function () {
var gyt = $("#textEditor").contents().find("body").html().match(/#/g);
if ($("#textEditor").contents().find("body").html().match(/#/g) >= 0) { } else {
$("#text").val($("#textEditor").contents().find("body").html());
}
$("#text").val($("#textEditor").contents().find("body").html());
}, 1000);
I don't want use third party text editor plugins. in short I want texteditor which contain a button, after clicking this button it will wrap new text with div tag with specified class or id. something like Stack Overflow text editor...with facility of adding custom div with specified class or id.
<html>
<head>
<style>
#Problem{margin: 5px; outline: 1px dotted red; padding: 5px}
#Solution{margin: 5px; outline: 1px dotted green; padding: 5px}
#Solution textarea{
height: 200px;
width: 500px;
}
</style>
<script>
//Wraps the text in a new div with optional id and classname.
//Returns the new div.
function wrapMe(text, id, classname){
var tE = null;
if (text && text.trim() != ''){
tE = document.createElement('div');
tE.id = (id || '');
tE.className = (classname || '');
tE.innerHTML = (text || '');
}
return tE
}
//Adds the outer html of passed element to the textarea with a linebreak
function addElementToTextarea(e){
var tA = document.querySelector('textarea');
if (tA && e){
tA.innerHTML = (tA.innerHTML || '') + e.outerHTML + '
&#010'
}
}
</script>
</head>
<body>
<div id = 'Problem'>
Problem: I don't want use third party text editor plugins. in short i want texteditor which contain a button, after clicking this button it will wrap new text with div tag with specified class or id. something like stackover flow text editor...with facility of adding custom div with speicifed class or id.
</div>
<div id = 'Solution'>
<input type = 'text' />
<button onclick = "addElementToTextarea(wrapMe(this.parentNode.querySelector('input').value, 'testid', 'testclass'))">Wrap me</button>
<br /><br />
<textarea readonly = 'readonly'></textarea>
</div>
</body>
</html>

Categories

Resources