No errors but JavaScript still doesn't work [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 3 years ago.
When the user clicks on the like button I want to show a notification above "Mijn verhalen" to let the user know it liked a certain thing. I don't know what's wrong because there are no errors in my JavaScript. But the notification doesn't show up...
This is the JavaScript code:
var een =
document.getElementsByClassName('like');
var popup =
document.getElementsByClassName('toevoegen');
een.addEventListener('click', function() {
popup.classList.toggle('toevoegen');
});
img.toevoegen {
position: absolute;
right: 5em;
top: 4em;
width: 10em;
}
<button class="like"></button>
<img class="toevoegen" src="images/een.png">

var popup = document.getElementsByClassName('toevoegen');
document.getElementsByClassName returns HTMLCollection which is nothing but array. classList is not a known property of HTMLCollection.
You need to get the first element of this HTML collection and use the classList property. First element is nothing but the popup element.
Or else provide ID to the img tag and access it using document.getElementById which returns a DOM element not an HTML array collection.
var een =
document.getElementsByClassName('like');
// get the first pop up element here
var popup =
document.getElementsByClassName('toevoegen')[0];
een.addEventListener('click', function() {
popup.classList.toggle('toevoegen');
});

Related

Append the textContent of every anchor of a class to it's href [duplicate]

This question already has answers here:
How to correctly iterate through getElementsByClassName
(10 answers)
Closed last month.
HTML (I'm writing in a combination of Markdown & HTML).
- Ex. **<a class="kanji">犬</a>が**好き ・ I like dogs.
- Ex. **<a class="kanji">私</a>は**オーケーです・**I am** okay
JavaScript
const kanjiAnchor = document.getElementsByClassName("kanji")
for (var i = 0; i < kanjiAnchor.length; i++) {
kanjiAnchor[i].href = `https://jisho.org/search/${kanjiAnchor.textContent}`
kanjiAnchor[i].target = "_blank"
}
The above code returns an href of "https://jisho.org/search/undefined". I was able to do this on a smaller scale only selecting a single anchor with `document.getElementById("kanji"), but I want this to be done to every anchor tag with the class "kanji".
You need to access the textContent of the current element rather than the collection of elements.
kanjiAnchor[i].href = `https://jisho.org/search/${kanjiAnchor[i].textContent}`

javascript DOM out of sync? [duplicate]

This question already has an answer here:
Javascript Console Log reporting object properties incorrectly
(1 answer)
Closed 1 year ago.
I'm playing with JavaScript and DOM for a (high school) class I'm teaching. Emphasizing that students use console.log for diagnostics. However, in using it I find the values retrieved from the DOM to be out of sync with the UI.
In the SSCE below, when the LI element is clicked, the first time it should log that the style is "color:red;", but it says style is "text-decoration:line-through;". I added the alert() to give time for anything async to finish but no joy.
If I remove the if( isOn ) clause, the attributes print out as expected, and after the first click attributes also print out as expected.
Guessing there's some synchronizing that needs to happen, just not sure what it may be ...
var theLi = document.getElementById("here");
theLi.addEventListener("click", crossOff);
theLi.setAttribute("style", "color:red;");
theLi.setAttribute("crossed", "off");
function crossOff(element) {
var isOn = this.getAttribute("crossed") == "on";
var attrs = this.attributes;
for (const attr of attrs) {
console.log(attr);
}
alert("huh??");
if (isOn) {
this.setAttribute("style", "text-decoration: none;");
this.setAttribute("crossed", "off");
} else {
this.setAttribute("style", "text-decoration: line-through;");
this.setAttribute("crossed", "on");
}
}
//Write function crossOff here.
<!DOCTYPE html>
<html>
<body>
<h3>To Do List:</h3>
<ul>
<li id=here>Eat</li>
</ul>
<script>
</script>
</body>
</html>
The problem would be that you are logging attribute nodes, which are still linked to the DOM. The console is known to render its output asynchronously, as well as to display DOM elements in a "user-friendly" representation - notice you can even edit them just like in the DOM inspector ("Elements" panel)!
This becomes more clear when you use console.dir instead, and explicitly expand the properties of the object:
In your particular case, don't log the attribute node but rather its contents, like name and value.

How To Grab Image Source From CSS Background Image [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
This is my first question ever, please show some love!
I'm trying to grab the background image from a div element and append it to a div every time I push a bottom. Below is the mockup code:
<div class="img"></div>
.img {
background: url("local image file");
}
function addImage(imageSrc) {
var imageSrc = document.getElementByClassName('img')[0].getComputedStyle.background
}
I could not find a way to grab the local path inside the background url(""). Can someone please help? I only know vanilla Javascript.
Thank you!
Using the getComputedStyle on the window.
const img = document.getElementsByClassName('img')[0];
const url = getComputedStyle(img).backgroundImage.slice(5, -2);
I get the URL from getComputedStyle(element).backgroundImage then slice out the url and brackets surrounding the link
Use:
window.getComputedStyle(document.getElementsByClassName('img')[0]).getPropertyValue('background')
getComputedStyle is a property of window. Since window is always implicit, it can be omitted. Here's your solution:
const imgSrc = getComputedStyle(document.querySelector('.img')).backgroundImage.slice(5, -2);
console.log(imgSrc);
.img{
background:url('test.png');
}
<div class='img'></div>

Query Selector, select an element by it's class and content [duplicate]

This question already has answers here:
Native javascript equivalent of jQuery :contains() selector
(6 answers)
Closed 3 years ago.
I'm making a chrome extension and i want to do an action when a certain element exist on the page. But the class element isn't precise enough to select the element only by it's class.
the element i'm looking for on pages is the following :
<span class="btn-text">M'y emmener</span>
I tried :
const listfull = document.querySelector('.btn-text:contains("m\'y emmener")');
if (listfull) {
console.log("hello")
}
But it doesn't seems to work anybody could tell me how this works ?
:contains is jQuery-specific syntax. It's also case-sensitive. To achieve what you're looking for, either use jQuery and capitalize the M:
const listfull = $(`.btn-text:contains("M'y emmener")`);
if (listfull.length) {
console.log("hello")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="btn-text">M'y emmener</span>
Or iterate over all matches of .btn-text and check their textContent:
const listfull = [...document.querySelectorAll(`.btn-text`)]
.find(elm => elm.textContent.includes("M'y emmener"));
if (listfull) {
console.log("hello")
}
<span class="btn-text">M'y emmener</span>

Simple JS code bug [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 6 years ago.
why dose not it work ? !!
i want to make images fade out when it is loaded , i know that this can be done by jQuery , but i wanna know where is the bug in this code.
<img src="http://1.bp.blogspot.com/-M03SoTLlJ4k/Vfwvq2dz42I/AAAAAAAAD9I/o-xN8x6HL2Y/s1600-r/Untitled-1%2B%25281%2529.png" onload="loadimage()" id="imageid"/>
<style>
#imageid {
opacity:0;
transition:1s;
}
</style>
<script>
function loadimage(){
document.getElementsByTagName("img").style.opacity="1"
}
</script>
getElementsByTagName returns a NodeList not a single DOM node, hence you need to do getElementsByTagName('img')[0] for example to get the first img, then apply the styles on that element.
Update
select all images
if you want to select all the images and apply styling to them
function loadimage(){
var imgElements = document.getElementsByTagName('img');
for(var i=0, l=imgElements.length; i < l; i++) {
imgElements[i].style.alpha = 1;
}
}
only currently loaded image (preferred by me)
function loadimage(){
this.style.alpha = 1;
}
In javascript,
document.getElementsByTagName('img')
returns a nodelist.
If you want the first item in that nodelist, you need to write:
document.getElementsByTagName('img')[0]

Categories

Resources