javascript issue getElementById to modify CSS - javascript

I have an issue about getElementById.
Here is the part of the javascript code that causes a problem:
var elmt = document.getElementById("cardSlotsJoueur");
elmt.style.backgroundImage = "url('images/backcard.png')";
I wanted to modify this (Css) :
#cardSlotsJoueur div {
But it actually modifies #cardSlotsJoueur {
Could you help me to find a way to modify the first one with getElementById ?
Thanks !

If you only want to modify the first div within the element with id=cardSlotsJoueur, you can use this:
var elmt = document.getElementById("cardSlotsJoueur").getElementsByTagName("div")[0];

To target #cardSlotsJoueur div it's better to use querySelector method which would retrieve children div element of the #cardSlotsJoueur container:
var elmt = document.querySelector("#cardSlotsJoueur div");
If you expect multiple div elements under the #cardSlotsJoueur then you need to get them all first
var elmt = document.querySelectorAll("#cardSlotsJoueur div");
and then set backgroundImage to each in the for loop.

You need to find div elements within #cardSlotsJoueur:
var elmt = document.getElementById("cardSlotsJoueur");
var divs = elmt.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
divs[i].style.backgroundImage = "url('images/backcard.png')";
}

Probably the best way to do what you want is to use a class with the required styling and add it to the element. But as an alternative, you can add a rule to the last style sheet, e.g.
function addBackground() {
var sheets = document.styleSheets;
// If there are no style sheets, add one
if (!sheets.length) {
document.head.appendChild(document.createElement('style'));
}
// The sheets collection is live, if a new sheet was needed, it's automatically a member
sheets[sheets.length - 1].insertRule('#cardSlotsJoueur div{background-image:url("images/backcard.png")');
}
You can make it generic:
function addRule(ruleText) {
var sheets = document.styleSheets;
if (!sheets.length) {
document.head.appendChild(document.createElement('style'));
}
sheets[sheets.length - 1].insertRule(ruleText);
}
and call it like:
addRule('#cardSlotsJoueur div{background-image:url("images/backcard.png")');

Related

How to target a data-ref with a specific value and add a style using javascript

I want to target a data-ref with a specific value and add an inline style="display:none;" to it.
How can this be achived? Can someone help me please?
This is how it looks:
<div data="{test-bubble}}" data-ref="bubbles[test-link.com/test]" class="bubbles" state="default">
</div>
I tried this but it does not work:
var bubbleremoval = document.querySelector('[data-ref="bubbles[test-link.com/test]"]')
bubbleremoval.style.display = "none";
"""Your code should work if you are applying to a single element since query selector returns one element but for several elements you could fetch by classname and loop through the elements and remove display for each"""
var bubbleremoval = document.getElementsByClassName('bubbles')
for (let i = 0; i < bubbleremoval.length; i++) {
bubbleremoval[i].style.display = "none";
}

How to select an element with specific css value in javascript

I want to select an element if it has a css as display block then do this function. If the element has the css as display block then remove ('hide') class from the header class.. This is what I want to do.. Any help?
Well, there are two solutions depending on what you want:
Solution 1
Looping through all elements and removing hide class from the current element if it has display block value in its style.
var elements = document.getElementsByTagName("*");
for(let i = 0; i < elements.length; i++) {
if(elements[i].style.display == "block") {
elements[i].classList.remove("hide");
}
}
Solution 2
Getting the reference of the element via HTML id.
var element = document.getElementById("YourElementID");
if(element.style.display == "block") {
element.classList.remove("hide");
}
You can define an id like this in your HTML file:
<div id="YourElementID">Div</div>
I am assuming that you want to determine if the element has the "hide" class by checking its display style. you don't need to do that, you can easily check its class list by using the following code:
element.classList.contains("hide");
There are several ways of collecting all the elements with display: block and i am not sure, which one performs best - or whether it performs good at all.
If you want all the Element instances of the page, which have a computed style of display: block you can do something like:
var $els = Array.from(document.body.querySelectorAll('*')).filter(function($el) {
return getComputedStyle($el).display === 'block';
});
Or ES6:
const $els = Array.from(document.body.querySelectorAll('*')).filter($el => getComputedStyle($el).display === 'block');
If you want the Element instances which have display: block literally set in the style-attribute, you have to do something like this:
var $els = Array.from(document.body.querySelectorAll('*')).filter(function($el) {
return $el.style.display === 'block';
});
I think it would perform better, if the selector in querySelectorAll() would be a little more specific.
Another option would be to use the TreeWalker API, but then you have to do a mutation, because you have to iterate over all the elements and push them to an array:
var $els = [];
walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
while (walker.nextNode()) {
if (getComputedStyle(walker.currentNode).display === 'block') {
$els.push(walker.currentNode);
}
}
Once you have all your elements, you can do something with them.
A little bit more information would be helpful, especially what exactly you want to achieve, once you have the elements, because then i could also provide more help. Maybe provide a code example?

Adding new element to nested classes

I need to use JS to create a new element within specific nested classes in HTML. So in this example, I need to create a new span with the class of "paw-print" only where the "collies" class is nested within "dogs".
Here's what I have so far: https://jsfiddle.net/p50e228w/6/
The problem is that my current JS works on the first instance, but not on the other. I currently have document.getElementsByClassName set to "collies" but I need to target that class only when it's inside the parent "dogs" class.
What am I missing here?
var span = document.createElement("span");
span.className = "paw-print";
var wrap = document.getElementsByClassName("collies");
for(var i = 0; i < wrap.length; i++) {
wrap[i].appendChild(span);
}
I can use jQuery, but I've been using vanilla JS just because I'm such a noob and want to understand what my code is doing.
There are 2 issues with your code.
Positioning : The images are being given a absolute position, and they rest in the same position based on the page layout. So set relative positioning for the parent container.
CSS
.relative {
position: relative;
}
You need to append that to parent element which is collie here.
You can use querySelectorAll to find the nested relation ship that you are looking for.
var collies = document.querySelectorAll('.dogs .collies');
for (var i = 0; i < collies.length; i++) {
var span = document.createElement("span");
span.className = "paw-print";
collies[i].appendChild(span);
}
Fiddle
If you want to append to parent ( element with class 'dog')
$('.dogs .collies').each(function() // finds elements in the dom with parent element 'dog' and it's child element 'collies'
{
$(this) // 'this' would represent 'collies' element
.closest('.dogs') // .closest('.dogs') would get it's nearest occurence in the heirarchy ( basically it's parent )
.append($('<span/>', { class: 'paw-print'})); // create a dynamic span element and append to 'this'
});
If you want to append to child( element with class 'collies')
$('.dogs .collies').each(function()
{
$(this).append($('<span/>', { class: 'paw-print'}));
});
In addition to this, you also need to set position: relative as pointed out by Rob.
Example : https://jsfiddle.net/DinoMyte/1zxn8193/1/

How can I get an element's attribute from the parent's parent element's ID using JavaScript?

So I have the following HTML...
HTML:
<div id="col1">
<img src="1.jpg">
</div>
And I am implementing a HTML5 drag and drop feature where the inner html of col1 is changed for the dragged element's inner html - so basically the columns change their content.
I have another div (let's call that swap-text) where I want to change its text content depending on what image is presently inside col1.
This is why I want to figure out how I can obtain col1's img element's src attribute value through JavaScript so I can then write an if statement to change the content of the swap-text depending on which image is in col1.
I could add ID's to the img elements but then I still don't know how I would write the condition to check if say, img-id1 parent is col1.
Attempt(s):
var doc = document.getElementById("col1");
var children = null;
var imgEle;
//gets img node, but also got 1/2 text object(s)?
for (var i = 0; i < doc.childNodes.length; i++) {
children = doc.childNodes[i];
console.log(children);
}
//document.getElementById("img")
//children[1].getAttribute('src'); - cannot call method 'getAttribute' of undefined
//imgEle = doc.childNodes[0].getElementById('img'); - Object #<Text> has no method 'getElementById'
console.log(imgEle);
console.log(children);
This work fine pure javascript:
document.getElementById("col1").getElementsByTagName("img")[0].getAttribute("src");
var doc = document.getElementById("col1");
var img = document.getElementsByTagName('img')[0];
var imgParent = img.parentElement;
This is how you determine the elements parent/
I suggest you to use JQuery so you can simply use:
$("img").attr("id"); //Return the id of the img element
Check this:
var column = document.getElementById("col1");
var imgSrc = column.getElementsByTagName("img")[0].getAttribute("src");
Or just use the jQuery - it's simpler:
$('#col1 img').attr('src');
as you will only have one child node in col1 (the img), change the for loop.
var doc = document.getElementById("col1");
var children = null;
var imgEle;
//gets img node, but also got 1/2 text object(s)?
//for (var i = 0; i < doc.childNodes.length; i++) {
// children = doc.childNodes[i];
// console.log(children);
//}
childen = doc.childNodes[0];
// or children = doc.firstChild;
console.log(children);
//document.getElementById("img")
console.log(children.getAttribute('src')); - children is single object
//imgEle = doc.childNodes[0].getElementById('img'); - Object #<Text> has no method 'getElementById'
console.log(imgEle);
console.log(children);

get element after page loads

how do i call a function to count the number of divs with an id of 'd1' after the page loads. right now i have it in my section but doesnt that execute the script before anything in the loads? because it works if i put the code below the div tags...
Firstly there should be at most one because IDs aren't meant to be repeated.
Second, in straight Javascript you can call getElementById() to verify it exists or getElementsByTagName() to loop through all the divs and count the number that match your criteria.
var elem = document.getElementById("d1");
if (elem) {
// it exists
}
or
var divs = document.getElementsByTagName("div");
var count = 0;
for (var i = 0; i < divs.length; i++) {
var div = divs[i];
if (div.id == "d1") {
count++;
}
}
But I can't guarantee the correct behaviour of this because like I said, IDs are meant to be unique and when they're not behaviour is undefined.
Use jQuery's document.ready() or hook up to the onLoad event.
well an ID should be unique so the answer should be one.
you can use <body onload='myFunc()'> to call a script once the DOM is loaded.
You need to have the function tied to the onload event, like so:
window.onload = function() {
var divElements = document.getElementById("d1");
var divCount = divElements.length;
alert(divCount);
};
For the record, you should only have one div with that ID, as having more than one is invalid and may cause problems.

Categories

Resources