Add CSS class to JS script and Trigger With Button (night mode) - javascript

In my header.php template, I have a button that looks like this, in my stylesheet, I have the following CSS code and In an already enqueued JS file, I have this:
function NightModeToggle(){
var element = document.body;
element.classList.toggle("NightModeToggle");
}
.NightModeToggle{
background-color: black;
color: white;
}
<button onclick="NightModeToggle()">Dark</button>
I understand that it targets the body by using this line: var element = document.body;
My question is, how do I add additional targets so that I can change the background color and text color of the header and footer as well?
I tried modifying the code into this (without result):
var element = document.body;
var element = document.header;
var element = document.footer;
Any ideas?

Depending on the structure of your HTML, you will need to target your other elements by using document.querySelector() and passing in the selector of the element you want to target, e.g.:
document.querySelector('footer') // If you use a <footer> tag
document.querySelector('#footer') // If you use e.g. <div id="footer">
document.querySelector('.footer') // If you use e.g. <div class="footer">
You can also use document.querySelector('body') instead of document.body to keep this approach consistent.
The reason document.body works is that body is a property of the document object that contains the contents of the document (the <body> tag). Similarly, document.head will return the content of the <head> tag in your HTML.

Related

How do I append a div container to a specific area of a webpage?

I am asking this question because all of the other answers that I found are dealing with JQuery. I am not using JQuery, just pure JS.
Currently I create a div and add content into the div using Create Element and innerHTML. I then use appendChild on the body of the document to add the HTML to the document. The issue is that the injected HTML is at the very bottom of the body but I want it at the top.
How can I do this?
EDIT:
My code:
// Content-Script Function: This function toggles the extention on and fetches the required resources from the server.
function toggleExtOn() {
//Get url for the html page.
let url = chrome.runtime.getURL("flipfinder.html");
//Create the container.
var flipfinderContainer = document.createElement('div');
//Set the id.
flipfinderContainer.setAttribute("id", "flipfinderContainer");
//Add the html to the div using iframe.
flipfinderContainer.innerHTML = "<h1>Hello</h1>";
//Append the div to the pages html body.
document.body.appendChild(flipfinderContainer);
}
You can use the prepend function to prepend the element to your div. Prepending is like appending but it adds to the start instead of the end.
For example:
const element = document.createElement("img");
document.body.prepend(element);
Instead of using .appendChild() which will always add to the end, you can use .prependChild() and add your div BEFORE the body.

Using JS how can I select a HTML 5 element?

Edit: I am totally new to JavaScript. I've spent ages looking to solve my issue, but don't know the right words or phrases to ask the 'correct' question. Other vaguely similar questions are not at all clear and not as specific as my question: how to select the nav.
I have some JS to add a class to my <nav>:
<script>
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.add("mystyle");
}
</script>
This means I have to add an ID to my <nav> resulting in
<nav id="myDIV">
Is there a way to not have to add an ID to the <nav>? For the JS to select the <nav> element without having to add an ID?
I guess it would be something like this:
var element = document.getElementByType("nav");
For that you could use querySelector, which takes a CSS selector as a parameter
var element = document.querySelector("nav");
element.classList.add("mystyle");
If that nav is a child of e.g. a header, you could add its selector to grab only nav that is within such parent
var element = document.querySelector("header nav");
element.classList.add("mystyle");
It is situations like the latter where it really excel's with its CSS selector parameter
var element = document.getElementByType("nav");
The method you are looking for is getElementsByTagName which returns a list of all the elements with a matching tag name.
var elements = document.getElementsByTagName("nav");
var first_nav = elements[0];
console.log(first_nav);
<nav></nav>
You could also use querySelector which returns the first element matching a CSS selector.
var first_nav = document.querySelector("nav");
console.log(first_nav);
<nav></nav>
You can use getElementsByTagName or querySelector
document.getElementsByTagName("nav")[0].classList.add("mystyle");
document.querySelector("nav").classList.add("mystyle2");
.mystyle {
color: red;
}
.mystyle2 {
font-size: 18px;
}
<nav>Nav</nav>

jQuery: using .css on a cloned element to obtain a specific css property?

I am trying to obtain the font-size currently applied to a cloned element, but when I use the jQuery .css function, it doesn't retrieve anything.
Is it not possible to use the ".css" function in jQuery to retrieve a specific css property from a cloned element?
The following does not work:
var clonedElement = jQuery('.element').clone();
clonedElement.attr("style", "");
var defaultFontSizeValue = clonedElement.css('font-size');
console.log(defaultFontSizeValue);
Edit 1
The original unfortunately has inline styles that don't allow me to get the overridden font-size property for that element that is applied via a class. This is why I am trying to retrieve that original value by removing the inline styles in the clone.
Your problem is that the cloned element is not "attached" to your dom, and therefore there is no style definition to this element (based on css that are not inline).
What you can do is append the cloned element to the body (after setting display: hidden, if you want), and then check the font-size:
$(function() {
console.log($('.c1').css('fontSize'));
c1 = $('.c1').clone();
console.log(c1.css('fontSize'));
c1.css('display', 'none');
$('body').append(c1)
console.log(c1.css('fontSize'));
});
.c1 {
font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="c1">asd</div>

How to disable all styles for specific group of elements

is it possible to disable css styles for specific group of html elements?
To be more specific, I have html document and many css styles and I want to set default css for some elements (or remove/disable all styles for those elements).
Is there any way to do this using html/css/javascript? Setting all styles to default one by one takes time.
In addition I can say that it can be done by nesting part of code to iframe (because it doesn't inherit styles) but it is not much pretty way at all.
Thanks for help.
Add a class to the <body> tag?
HTML
<body class="default-theme">
<p> ... </p>
<ul>
<li> .. </li>
<ul>
</body>
CSS
body.default-theme p {
... default settings ...
}
body.default-theme li {
.. more css ...
}
How are the elements grouped? Is it by a particular class name? If so you could do the following to clear out the style's or set them to a particular value
var all = document.getElementsByTagName('theClass');
for (var index in all) {
var element = all[index];
element.style = {};
}
If you control the stylesheet, then you can just make all the styles depend upon a master class in the body element. Then, you can turn all those rules on/off by simply adding or removing that class from the body element.
Suppose the class name is "master". When the "master" class name is on the body element like this:
<body class="master">
then all these rules will be in force:
.master .selected {color: blue;}
.master #breadcrumb {color: red;}
If you then remove the "master" class from the body tag with script, all those rules will stop being applied instantly.
Obviously, you don't have to use the body tag. You can use any common parent object of all the effected elements.

Adding HTML elements with JavaScript

So, if I have HTML like this:
<div id='div'>
<a>Link</a>
<span>text</span>
</div>
How can I use JavaScript to add an HTML element where that blank line is?
node = document.getElementById('YourID');
node.insertAdjacentHTML('afterend', '<div>Sample Div</div>');
Available Options
beforebegin, afterbegin, beforeend, afterend
As you didn't mention any use of javascript libraries (like jquery, dojo), here's something Pure javascript.
var txt = document.createTextNode(" This text was added to the DIV.");
var parent = document.getElementById('div');
parent.insertBefore(txt, parent.lastChild);
or
var link = document.createElement('a');
link.setAttribute('href', 'mypage.htm');
var parent = document.getElementById('div');
parent.insertAfter(link, parent.firstChild);
Instead of dealing with the <div>'s children, like other answers, if you know you always want to insert after the <a> element, give it an ID, and then you can insert relative to its siblings:
<div id="div">
<a id="div_link">Link</a>
<span>text</span>
</div>
And then insert your new element directly after that element:
var el = document.createElement(element_type); // where element_type is the tag name you want to insert
// ... set element properties as necessary
var div = document.getElementById('div');
var div_link = document.getElementById('div_link');
var next_sib = div_link.nextSibling;
if (next_sib)
{
// if the div_link has another element following it within the link, insert
// before that following element
div.insertBefore(el, next_sib);
}
else
{
// otherwise, the link is the last element in your div,
// so just append to the end of the div
div.appendChild(el);
}
This will allow you to always guarantee your new element follows the link.
If you want to use something like jQuery you can do something like this:
$('#div a').after("Your html element");
jQuery has a nice, built in function for this: after(), at http://api.jquery.com/after/
In your case, you will probably want a selector like this:
$('#div a').after('<p>html element to add</p>');
The code examples from the link given above also show how to load jQuery if that is new to you.
Element#after can be used to insert elements directly after a certain HTML element.
For example:
document.querySelector("#div > a").after(
Object.assign(document.createElement('div'), {textContent: 'test', style: 'border: 1px solid'}));
<div id='div'>
<a>Link</a>
<span>text</span>
</div>
Assuming that you are only adding one element:
document.getElementById("div").insertBefore({Element}, document.getElementById("div").children[2]);

Categories