Simple question really, I'm using the getElementById to target my div standby and change its styling. Now, I can't for the love of anything find out how to target what is written in my CSS as #standby img, that is, the img tag within standby. How would I target this and change its styling with JavaScript?
For plain javascript in all browsers, it would be this:
var imgs = document.getElementById("standby").getElementsByTagName("img");
In more advanced browsers, you could use this:
var imgs = document.querySelectorAll("#standby img");
Each of these returns a nodeList (which is like an array of DOM elements) that you can then iterate over.
You could then iterate the results of either of these like this:
for (var i = 0; i < imgs.length; i++) {
imgs[i].style.width = "300px";
}
If you know there is one and only one image in that div, then you could just do this rather than iterating over more than one:
document.getElementById("standby").getElementsByTagName("img")[0].style.width = "300px";
Use document.querySelector for a pure javascript solution:
document.querySelector("#erg img");
You can then change its style like you would with an element retrieved with getElementById.
You can do this easily with jQuery. $('#standby img'). Worth looking into.
So you've already got the standby element using getElementById().
To get the img elements within it, you need to use getElementsByTagName()
var standby = document.getElementById('standby');
var standbyImgs = standby.getElementsByTagName('img');
I guess you already have the first line, so you just need the second. Or combine them into one.
Important to note that getElementsByTagName() returns an array of elements, not a single element like getElementById(). Because obviously, there could be more than one img there, whereas there should only ever be one element with a given ID.
Related
I have a Wordpress site with a background in the header inside of a class.
I'm tring to write a bit of JS to change this background image depending on a hashtag. The Hashtag script is working but the change BG bit isn't - please help... :-(
The script I've writen is:
document.getElementsByClassName("eut-bg-image").style.backgroundImage = "url(https://boutiqueballer.com/wp/wp-content/uploads/2017/10/chanel.jpg)";
})();
getElementsByClassName yields a collection of elements. The individual elements in the collection have the style property, not the collection itself. If you are targeting just one element, you can access it by index:
document.getElementsByClassName('eut-bg-image')[0].style.backgroundImage = ...;
If you are targeting several elements, you may iterate over them:
var elements = document.getElementsByClassName('eut-bg-image');
for(var i = 0; i < elements.length; i++)
elements[i].style.backgroundImage = ...;
Alternatively, you may use document.querySelector, depending on which level of browser compatibility you need. You can then distinguish between document.querySelectorAll if you want a collection, or docment.querySelector if you want only the first match. Accepts a CSS selector:
document.querySelector('.eut-bg-image').style.backgroundImage = ...;
Is it possible to get all the elements from a webpage, and make a variable for each one? can you make variables within an each function and name them the same as their element name?
Yes, but be careful.
It is useful to store an element reference in a variable if it's present at load time and not changed later, but removing the div after load would cause your variable to return undefined. If the div is added after the variable is declared, you will also encounter an error.
Have a read here.
As you said, it's just for fun.. so I think that this should do the trick:
$("*").each(function() {
const elmnt = $(this);
const id = elmnt.attr("id");
if(id) {
window[id] = elmnt;
}
});
This will only create variables for the DOMs that have the id defined. But you can change the rule the way you want.
Use:
var div = $('div');
div.click();
If you wanted to bind the click event to all div elements you could easily just do:
var div = $('div');
div.click(function(){
//do something
});
A good way to shorten the jQuery selector and overhead and page performance is to use VanillaJS: http://vanilla-js.com/
Selecting object is one of the easiest thing to do with vanilla JS. I don't know what is your use case but a lot of what jQuery does is never used. If you are looking for optimization, try to live without it for a while and you might be surprised. Here are some out of the box ways to get elements in short variables.
Get all divs in your document:
var divs = document.querySelectorAll('div');
Get the first div only:
var div = document.querySelector('div');
Get a specific div:
var div = document.getElementById('somediv');
This way you can control everything (a la carte variables, rather than trying to solve all problems you might not need to solve).
I am trying to do a simple toggling of classes for multiple elements for a slide out menu without jQuery, pure JS.
function toggle_classes() {
var navicon = document.getElementById('nav-icon');
var overlay = document.getElementsByClassName('overlay');
navicon.classList.toggle('open');
overlay.classList.toggle('show');
}
document.querySelector('#nav-icon1').addEventListener('click', toggle_classes);
When I define the variables with getElementById it works, but it doesn't work with getElementsByClassName
Can someone tell me how to fix this? I'd much rather use getElementsByClassName so I can target multiple elements with a single line of code.
The data structure returned by getElementsByClassName is an array-like structure, not a dom element. so you must loop over the elements to toggle each one individually.
for (var i = 0; i < overlay.length; i++) {
overlay[i].classList.toggle(...)
}
document.getElementsByClassName... notice the "s" in Elements?
(in other words, that method returns an array, not a single element, so you need to do somehting like overlay[0].etc)
Is it possible to add an HTML ID via the browser console using DOM Manipulation?
For example, suppose I am dealing with the following element:
<div class="elementClass">
I can fetch via DOM with something like:
document.getElementsByClassName("elementClass");
However, is it possible to add an attribute via this type of method? If I inspect the element with chrome I can do it manually, but I am wondering if it's possible to inject that ID via JavaScript.
Thanks!
You can do:
document.getElementsByClassName("elementClass")[0].setAttribute("id", "some ID");
Yes you can modify attributes of an object (HTMLElement) via javascript
getElementsByclassName returns an array, simply iterate through the list and set the attributes you wish.
var elements = document.getElementsByClassName("elementClass");
for(var I = 0; I < elements.length; I++)
element[I].id = "element" + I;
Then you could access any of those elements with that class via
var element = document.getElementById("element" + 0); //Gets First Element
Sure.
document.getElementsByClassName('elementClass')[0].id = 'someID';
or
document.getElementsByClassName('elementClass')[0].setAttribute('id', 'someID');
Just know that if you grab elements using getElementsByClassName then it will return an array of elements (assuming any elements with the matching class exist) so modifying the array won't give you the result you want.
setAttribute() method on the DOM element should work just fine.
HTML
<div class="elementClass">
This is the content of elementClass
</div>
<button onclick="buttonClicked()">Click to add attribute id red to elementClass</button>
Javascript
function buttonClicked(){
document.getElementsByClassName("elementClass")[0].setAttribute("id", "red");
}
CSS
#red {
background-color: red;
}
PLAYGROUND
Note that manipulating the class attribute causes the browser to reflow, therefore it is worth mentioning to use setAttribute() wisely to not cause performance issue.
I'm new to javascript. I created this div called colorme. I can successfully color it via javascript. Now assuming i want to change the background of <p>...</p>, or <span>,etc how do i reach it via Javascript? (no jquery).
Like document.getElementById() would work on the div and i reach it. Now i cannot keep giving unique id's to all the elements. How do i reach the inner elements like <p> or <span>, etc?
<div id="colorme">
<p>Blah Vblah Blah Content</p>
<span>Blah Vblah Blah Content</span>
</div>
You can use the element that you've found as a context for getElementsByTagName.
var colorme = document.getElementById('colorme'),
spans = colorme.getElementsByTagName('span');
Note that spans is a NodeList -- similar to an array -- containing all the span elements within colorme. If you want the first one (indeed, the only one in your code sample), use spans[0].
You should check out the many DOM traversal functions provided in standard javascript.
Tutorial: http://www.quirksmode.org/dom/intro.html
Reference: http://reference.sitepoint.com/javascript/Node
and http://reference.sitepoint.com/javascript/Element
Although the answers do give good ways to do it for this specific case....
The issue you're facing is called DOM-traversal. As you know, the DOM is a tree, and you can actually traverse the tree without knowing in advance the element id/type/whatever.
The basics are as follows
el.childNodes to access a list of children
el.parentNode to access the parent element
nextSibling and previousSibling for next and previous sibling nodes
For further info, see [MDC DOM pages](
Here are three ways:
If you only care about decent browsers, document.querySelector (returns the first matching node) and document.querySelectorAll (returns a NodeList) - e.g. document.querySelector('#colorme p').
HTMLElement.getElementsByTagName() (returns a NodeList) - e.g. document.getElementById('colorme').getElementsByTagName('p')[0]
HTMLElement.children, etc. - document.getElementById('colorme').children[0] (.firstChild will probably be a text node, lots of fun DOM stuff to get into there, the quirksmode DOM intro linked to is good stuff).
It's quite simple: getElementsByTagName()?
You could use getElementsByTagName()
Loop through the children:
var div = document.getElementById('colorme');
var i, l, elem;
for (i = 0, l = div.childNodes.length; i < l; i++) {
elem = div.childNodes[i];
// Check that this node is an element
if (elem.nodeType === 1) {
elem.style.color = randomColorGenerator();
}
}
In this case you can use:
var colormeDiv = document.getElementById('colorme');
var e1 = colormeDiv.getElementsByTagName('p');
var e2 = colormeDiv.getElementsByTagName('span');
to get the two elements inside 'colorme' div.
getElementById is just one of JavaScript's DOM methods. It returns an HTMLElement DOM object which you can then query to find child, parent and sibling elements. You could use this to traverse your HTML and find the elements you need. Here's a reference for the JavaScript DOM HTMLObject.
[after answering, I realised this is no answer to your fully explained question, but it is the answer to the question raised in the title of your post!]
One nice way of doing this is declaring a global var on the top of your Javascript that refers to the document, which can then be used everywhere (in every function):
<html>
<head>
<script type="text/javascript">
// set a global var to acces the elements in the HTML document
var doc = this;
function testIt()
{
doc.blaat.innerHTML = 'It works!!';
}
</script>
</head>
<body>
<div id="blaat">Will this ever work..?!</div>
<button onclick="testIt()">Click me and you'll see!</button>
</body>
</html>
As my first impression when I got to 'getElemenyById()' was that it sounds like a function that will iterate through the DOM's element list until it finds the element you need; this must take some time. With the above example, you simply access the element directly.
I'm not sure if I'm really saving CPU / adding speed this way, but at least it feels that way :)