Using JS how can I select a HTML 5 element? - javascript

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>

Related

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

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.

DOM manipulation - Center H1 element using javascript

How can I center my h1 using javascript?
h1 is <h1>Instrument track Recommendations</h1>, I tried below and it does not work.
var centeredH1 = document.getElementsByTagName("h1");
centeredH1.style.textAlign = "center";`
I know it would work with an ID using document.getElementById("h1id"); if I had one but I don't have an ID to work with.
getElementsByTagName returns an array-like object. If you have only one element, it will return an array-like object with one element. You need to get the [0] indexed element in that object. But as you have mentioned, it will be better to work with id in this case, if you want to attach styles only to one element.
var centeredH1 = document.getElementsByTagName("h1")[0];
// -------------------------------------------------^^^
centeredH1.style.textAlign = "center";
<h1>Test</h1>
DEMO
JAVASCRIPT
var h1s = document.getElementsByTagName("h1");
h1s[0].style.textAlign="center";
HTML
<h1>
THIS IS TO BE CENTERED
</h1>
You need to access first element from array returned by javascript getElementsByTagName

Javascript: How to append childs to section element?

Assuming that I have the following HTML:
<body>
<section role="main">
</section>
</body>
1) Can I do this?
var section = document.getElementsByTagName("section");
2) Can I do this?
var section = document.querySelector("section[role=main]");
3) And finally, how can I append childs to this element? appendChild() doesn't work.
var p = document.createElement("p").innerText("A paragraph.");
section.appendChild(p);
You can use either 1 or 2,
Using getElementsByTagName -
check out the fiddle - http://jsfiddle.net/2jzho6hh/3/
this one returns an array of all elements with tag name section, so to access the first section element you have to use the 0 index on the array. For the second element use 1 index on the array and so on..
Using querySelector,
check the fiddle - http://jsfiddle.net/2jzho6hh/2/
querySelector returns first element matching the selector you have specified as in this case section[role=main] which means select the first sectionelement with attribute role and its value being main
There is also one other method querySelectorAll which is, you may think, a union of above two methods. It selects elements on the basis of CSS selector syntax just like querySelector does and it returns an array of all elements matching the selector just like the getElementsByTagName
Correct code is
var p = document.createElement("p");
p.innerHTML="A paragraph";
section.appendChild(p);
don't add innerHTML at the time of declaring p.If you do so p will not return child node.Declare p as a node and then add innerhtml to it.

select html with native javascript

I want to toggle a class to the html tag element. I've made it work with the body element but I cannot find the solution to also toggle a class to the html tag.
document.querySelector('[data-menu-mobile]').addEventListener('click', function(){
document.body.classList.toggle('nav-main-mobile-open');
document.html.classList.toggle('html-color-fill');
});
I know this seems to be wrong:
document.html.classList.toggle('html-color-fill');
What is the correct way to do this?
There's no document.html object, to get to the root element you should use document.documentElement.
document.documentElement.classList.toggle('html-color-fill')
This should work:
var elements = document.getElementsByClassName("myclass");
//iterate through all found elements
Array.prototype.forEach.call(elements, function(element) {
element.className = "html-color-fill";
//or remove class with:
//element.className = "";
});

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