Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Child Selector?

KittenKatja

Well-Known Coder
I have only come this far:
JavaScript:
function setSelected() {
  event.target.parentElement.helpMeHere("clicked").classList.remove("clicked");
  event.target.classList.add("clicked")
}
The W3Schools says .children, .childNodes, and .childElementCount.

HTML:
<div>
    <a>1</a>
    <a class="clicked">2</a>
    <a>3</a>
</div>
<div>
    <a class="clicked">4</a>
    <a>5</a>
    <a onclick="setSelected()">6</a>
</div>
HTML:
<div>
    <a>1</a>
    <a class="clicked">2</a>
    <a>3</a>
</div>
<div>
    <a class="">4</a>
    <a>5</a>
    <a class="clicked" onclick="setSelected()">6</a>
</div>
 
Last edited by a moderator:
Code:
//to select all elements with given class
var children = document.querySelectorAll('.clicked');

for(var child of children){
    child.addEventListener('click', (event) => {
        //do stuffs here
    });
}
 
I believe, I encountered a problem I had before, too, but can't fix it this time.
JavaScript:
function setSelected() {let a = event.target;console.log(a.outerHTML);let b = a.parentElement.querySelectorAll("clicked").classList.remove("clicked");console.log(b.outerHTML);if(a.hasAttribute('class')){a.setAttribute('class')};a.classList.add("clicked");console.log(a.outerHTML)}
Only the first console.log gets written, and then the error says there's something wrong with remove() in setSelected(), setBackground(), and the HTMLAnchorElement.onclick
 
I believe, I encountered a problem I had before, too, but can't fix it this time.
JavaScript:
function setSelected() {let a = event.target;console.log(a.outerHTML);let b = a.parentElement.querySelectorAll("clicked").classList.remove("clicked");console.log(b.outerHTML);if(a.hasAttribute('class')){a.setAttribute('class')};a.classList.add("clicked");console.log(a.outerHTML)}
Only the first console.log gets written, and then the error says there's something wrong with remove() in setSelected(), setBackground(), and the HTMLAnchorElement.onclick
JavaScript:
function setSelected()
{
    let a = event.target;
    console.log(a.outerHTML);
    
    let b = a.parentElement.querySelectorAll("clicked").classList.remove("clicked");
    console.log(b.outerHTML);
    
    if(a.hasAttribute('class'))
    {
        a.setAttribute('class')
    };
    
    a.classList.add("clicked");
    console.log(a.outerHTML)
}

@KittenKatja It would make things a hell of a lot easier, for you, and for anyone looking at your code, to not minimize it into a one-liner. Yes, one-liners are awesome for performance and space saving, but are a pain in the you know what to debug. Hopefully now it has been expanded, I do hope you can see a few errors. Also, please post up any errors you are getting in console
 
JavaScript:
function setSelected()
{
    let a = event.target;
    console.log(a.outerHTML);
   
    let b = a.parentElement.querySelectorAll("clicked").classList.remove("clicked");
    console.log(b.outerHTML);
   
    if(a.hasAttribute('class'))
    {
        a.setAttribute('class')
    };
   
    a.classList.add("clicked");
    console.log(a.outerHTML)
}

@KittenKatja It would make things a hell of a lot easier, for you, and for anyone looking at your code, to not minimize it into a one-liner. Yes, one-liners are awesome for performance and space saving, but are a pain in the you know what to debug. Hopefully now it has been expanded, I do hope you can see a few errors. Also, please post up any errors you are getting in console
Off the bat, I can tell you one error that you will run into: if you are looking for just ONE element,
document.querySelector('.className') => this will return the first element with the given classname/id name

if you want all elements:
document.querySelectorAll('.className') => this will give you each node. NOTE: if you use this one, you are going to have to iterate through the list of elements.
 
Yeah, after posting the code, I saw an error in my code, but I had no idea on how to fix it, and waited for a response instead to fix it with the error together.

My current code is
function setSelected() {let a = event.target;console.log(a.outerHTML);let b = a.parentElement.querySelector(".clicked");b.classList.remove("clicked");console.log(b.outerHTML);if(a.hasAttribute('class') == false){a.setAttribute('class')};a.classList.add("clicked");console.log(a.outerHTML)}
Now it has a problem with classList at b.classList.
 
Yeah, after posting the code, I saw an error in my code, but I had no idea on how to fix it, and waited for a response instead to fix it with the error together.

My current code is
function setSelected() {let a = event.target;console.log(a.outerHTML);let b = a.parentElement.querySelector(".clicked");b.classList.remove("clicked");console.log(b.outerHTML);if(a.hasAttribute('class') == false){a.setAttribute('class')};a.classList.add("clicked");console.log(a.outerHTML)}
Now it has a problem with classList at b.classList.
Hey there, sorry for the late reply. Had an unexpected and tragic event happen to someone very close to me... but that is all I will say about it.
Let me ask you a question...out of curiosity, when you are coding, are you coding it as a one-liner all together, or do you code normally and then minify it when you post on here?
 
Hey there, sorry for the late reply. Had an unexpected and tragic event happen to someone very close to me... but that is all I will say about it.
Let me ask you a question...out of curiosity, when you are coding, are you coding it as a one-liner all together, or do you code normally and then minify it when you post on here?
This is why I ask:
1670047838481.png
so right off the bat, error on line 9 lol
So, where is 'event' being defined?
Also, what error are you getting relating to b.classList? Are you getting the 'cannot read attribute "classList" of undefined' error?
Also, you are missing a parameter in the function
JavaScript:
setAttribute('attributeName', value)

Goes without saying: including error messages and/or callstack along with code does wonders for the debugging process :)
 
I started coding like anyone else, in normal code writing format, but with tabs instead of spaces, in an older HTML language.
Then I started making Minecraft Resource Packs, both block/item models and languages. (also adding translation keys to my unfinished maps for accessibility to other languages than German and English)
Then I went over to Discord, found some bots with interesting features, first Tatsumaki, then blargbot, which Tatsumaki was based on.
Both transform plain text input into a coding language, which would allow me to make a bot use custom code, without the need to code a bot myself.
The code was notorious for not cleaning up spaces and breaks, and I just learned to never use breaks ever again.
This also changed how I code resource packs, breaking a line only as far in the back as possible, to make it look neat and less scroll intensive.
So basically, my Resource Pack and HTML code looks normal, my blargbot code is a one-liner, and my JS and Wallpaper Engine code are one-line functions.

setSelected() is used in setBackground() as the last thing, in which that is used in <a> elements, none have an ID or class, the parent <details> only has a class, which is indistinguishable to other <details> nodes.
I'm too lazy to add empty class attributes to these elements, so I use that part of the function to add an empty class attribute if needed, and then fill it in the next instruction. I didn't think, I would need to write an extra comma and an empty string to fulfill a requirement. I mean, I already added empty attributes to <a> elements I wanted to stand out. I added the comma with empty string value to your allegedly faulty suggestion, but the error persists the same.
The error says: "Uncaught TypeError: Cannot read properties of null (reading 'classList')"
It's possible that my code is written too far in the future, I mean, it first looks for a class that has yet to be created, and would only work once I click on another <a> element, but since it breaks before adding the empty attribute, it'll always return the same error.

What's a callstack?
 
I started coding like anyone else, in normal code writing format, but with tabs instead of spaces, in an older HTML language.
Then I started making Minecraft Resource Packs, both block/item models and languages. (also adding translation keys to my unfinished maps for accessibility to other languages than German and English)
Then I went over to Discord, found some bots with interesting features, first Tatsumaki, then blargbot, which Tatsumaki was based on.
Both transform plain text input into a coding language, which would allow me to make a bot use custom code, without the need to code a bot myself.
The code was notorious for not cleaning up spaces and breaks, and I just learned to never use breaks ever again.
This also changed how I code resource packs, breaking a line only as far in the back as possible, to make it look neat and less scroll intensive.
So basically, my Resource Pack and HTML code looks normal, my blargbot code is a one-liner, and my JS and Wallpaper Engine code are one-line functions.

setSelected() is used in setBackground() as the last thing, in which that is used in <a> elements, none have an ID or class, the parent <details> only has a class, which is indistinguishable to other <details> nodes.
I'm too lazy to add empty class attributes to these elements, so I use that part of the function to add an empty class attribute if needed, and then fill it in the next instruction. I didn't think, I would need to write an extra comma and an empty string to fulfill a requirement. I mean, I already added empty attributes to <a> elements I wanted to stand out. I added the comma with empty string value to your allegedly faulty suggestion, but the error persists the same.
The error says: "Uncaught TypeError: Cannot read properties of null (reading 'classList')"
It's possible that my code is written too far in the future, I mean, it first looks for a class that has yet to be created, and would only work once I click on another <a> element, but since it breaks before adding the empty attribute, it'll always return the same error.

What's a callstack?
Can you clarify what you mean by 'allegedly faulty suggestion'?
1670135063139.png

If you are getting the 'cannot read properties of null'...it means that the element that you are calling the classList attribute on, is null. This means that you need to look at a couple of things: 1) how you are querying the element, 2) whether the element you are trying to query is even loaded in DOM. It could be possible that you might have to look further up the chain and see if all elements are loaded.

NOTE to your SPOILER:
As I mentioned in many of my answers, one-liners (in terms of condensing multiple lines of code into one line) are great for performance and space saving in production, but a hell to debug lol. If you need help on any part of your code, please do not minify it lol. Trust me, there are many things that you can miss by doing so. You should always have your code de-minified while you code, and only minify when you are ready to push to production server. You will thank me in the long run :D

P.S: A callstack, for lack of better terms, is a list of calls being made. It's referred to as a stack because all the calls are listed as you would stack a bunch of plates. In a callstack, the last call made will always be at the top, while the first call made will be at the bottom. Knowing how to navigate the callstack will help you in debugging in any language.
 
Last edited:
I added a class="clicked" in one of the elements, and now everything works as intended, but what do I need to change to make it work even when there is no class="clicked" preexisting?
I mean, it must be something before the second console.log, since the first gets dispensed.
 
I added a class="clicked" in one of the elements, and now everything works as intended, but what do I need to change to make it work even when there is no class="clicked" preexisting?
I mean, it must be something before the second console.log, since the first gets dispensed.
ok so lets look at that snippet of code again, line by line
1670395679431.png
line 2: variable a: you are retrieving the target that triggered the click event.
line 4: variable b: you are retrieving variable a's parent element and querying it for the first instance of any element that contains the class 'clicked'.
line 5: you are attempting to remove the class 'clicked' from variable b's list of classes.

So, you would get the 'cannot read property x of null' at line 5 IF the code in line 4 fails to retrieve anything. This means that variable a's parent does not contain an element with the class 'clicked'. This begs the question: Assuming that you are attempting to add the class 'clicked' whenever a button is clicked, are you doing so correctly?
 
Assuming that you are attempting to add the class 'clicked' whenever a button is clicked, are you doing so correctly?
I can't tell how to fix that problem, when there doesn't already exist that property when the site is loaded.
The only other way I can think of is to add an empty element hidden from sight with that class for the sole purpose of fixing that dilemma.
And you are here just recounting events with 20/20 perfect hindsight.
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom