Input Field Not Deleting Dynamically using pure JS

Hello Fellas,

I’m trying to add some input fields dynamically, but when i try to delete wont work! shows me an error saying…
TypeError: document.getElementById(...) is null[Learn More]

I think its in the addEventListener(), but if i have it on the code inserted in the innerHTML will work!
'<input type="button" id="remove_kid" onclick="removekid(this)" value="Delete" />';
i want to do it independent. not inside the innerHTML.

So this is the code in a link…

Hope you all can help, want to know what im doing wrong.

The problem is, you are adding listeners to elements that do not exist, THEN adding those els. Instead, listen at the nearest static container. event.target will tell you which element, even dynamic ones, got the click.

Hi there!
So i will create another way to do it, not sure how to get it with an innerHTML on the fly so i will do it with createElements, might take sometime but i will update…

Thanks.

Not what i’m saying. You are creating them fine. But you have to listen for the click event on a parent node of your delete el, one that already exists when the script loaded. in that listener, compare event.target to your delete el – if they are the same, you know a delete was clicked, so figure which one to delete the associated input.

google “javascript event delegation MDN” to read more. The MDN isn’t required but they explain it well.

yes, i will try to goggle to find a solution, thanks…

Totally agree with snowmonkey. You should use event delegation.

I’m a visual learner, so I usually watch videos first, then dive into the docs for more info.
Here’s a good video explaining event delegation:
https://www.youtube.com/watch?v=mXTEVCg60zM (5 minutes 20 seconds)

Here’s an example with comments https://codepen.io/anon/pen/bzEbrq?editors=1010

2 Likes

Hello Fellas,
I have an update on this query, so i thank you for replying and helping me back @husseyexplores and @snowmonkey for the help and the guideness and information. so i have create another way around and it seems very good as well, a little more lines of code but those the job!. Let me know any comments or suggestions are welcome.

The code from @husseyexplores its the one i wanted to do at first cause, i wanted to do the delete button in an innerHTML, but i had an error now i know why i make a mistake.

I share my other solution i had:

Great work! :+1: Your solution is perfectly fine. I just want to point out a couple of things you can do to make it even better (not in terms of functionality, again because your solution is fine, but just best practices).

In your addItem function, you create li, then you create input, then you append input to the li, then you append that li to the DOM. and after that, you create delete button and append it to the DOM (again).

What you should do, is to also create the delete button, append it to the li, then append the li to the DOM at once. It’s considered good practice and also performant.
(Imagine you create a parent div, which contains 100 children, and you create each child one by one and append it to the DOM, that would be very bad. In terms of managing the code and also in terms of performance).

(And that just means moving your line #18 down to #26)

And you can also even use only one event listener instead of two. Won’t make any difference, but it will just help you learn event delegation more.

It will work as my previous example, although you would need to listen for the event either on the body or put the #adding-list div inside your container so the #items and ADD button live inside one parent that you can listen for clicks.

1 Like

Thank you so much!!! :wink: for giving me the advice that i need to make my coding more structured, your really helpful… i learn a lot from you… thanks so much getting into the habit of practicing and making more ideas that comes into my mind.
Yes i will deff look into your solution for a more professional way of handling the code. I’m looking forward to learn more about the event Delegation, for best practices as you said. and make that code better and easy to understand. How long have you been coding JS ? and how you became more familiar to it… how was your approach to it, i want to learn more…
i will to heard that you seem very good at it happy :slight_smile:

Thank you so much for your help…

Thank you for the kind words!

I started my coding journey in July 2018 properly. Before that, I only knew very basic HTML/CSS. I started with Udemy (I’m a visual learner as I mentioned) and took the first 3 courses of Jonas Schmedtmann, basic HTML/CSS course, Javascript course, and then advanced HTML/CSS course.

I can say that those courses built the foundation and gave me a some basic understanding of web development and how you should approach things. The reason I’m saying the ‘basic understanding’ is because usually one can only grasp 30% of the learnings, and you forget the rest. And that just comes with practice, you can’t remember 100% by just watching.

Just as I completed the courses, I started to freelance on Upwork (that I do till this day, working on one job right now! lol) and that’s when I started to polish my skills. (I only do small, customization related projects. No big projects as it doesn’t leave the time for me to learn and do other routine stuff)

After those courses and a little bit of practice, I tried The Odin Project, and went through the javascript algorithms section of that. And that’s when I knew I had ZERO knowledge of algorithms and data strucutres, as I’m not a CS graduate. I completed those with forum and youtube help and understood some of it though. (I only did Javascript section of The Odin Project as I was not interested in learning Ruby)

So I took another course on data structures and algorithms by Colt Steele. I must say it was a boring course, but was also AMAZING at the same time, as I understood about the data structures, algorithms, Big O notation etc, and that gave me a whole new perspective in terms of solving a problem.

I also took Wes Bos’ 30 days of Javascript course, (free course), which taught me some neat tricks too.

I started FCC on Sept 2018, did a few HTML/CSS challenges, but I found them very boring to be honest, as I knew much more advanced things, then I stopped. I continued FCC in January (yes, this month!) and aced through all the content, as I had the knowledge to do complete the challenges. I will complete the last project of front-end certification today or tomorrow hopefully. That means I earned 3 certificates in 17 days! lol. Here’s my progress: https://www.freecodecamp.org/husseyexplores

The rest is just practice, and practice. I’m focusing on React these days. Still far from perfect, but closer to my goals. Once I polish my React skills, I will dive into Node JS, and then look for a dev job, or maybe just after getting comfortable with React.

Imposter syndrome is like x10 for me, along with OCD :smiley: so whenever I do any job, I make sure I do it the correct way, and I only do it when I know I can deliver 100%, no exceptions.

For me, I took the FCC to get involved in the community and to test my skills (except Regex, I learned a lot on FCC about that. and I still suck at it). Data Visualization section will be new for me, so I’m excited about that!

It’s fair to say that from July 2018 to this day, there would be less than 5 days in which I didn’t do any practice.

It’s a journey at the end, not a marathon. Just keep going, know your knowledge gaps and fill them slowly, and focus where you want to go!

Again, I still don’t know a lot of things, but hopefully I will improve, and that’s what matters.

*I’m grateful for all these people, platforms like FCC, and The Odin Project, Youtube, Udemy MDN etc from I learned, free or paid, doesn’t matter. And I’m just paying it forward by helping others. This is one of the reason I’m here! And I admit I still learn things here on the forum, there are many more people that have way more knowledge than me! Like snowmonkey :slight_smile:

2 Likes

Why thanks, @husseyexplores – I’m not all that. I’ve been at it a little longer perhaps, I’ve broken a few more web pages and blown the CRAP out of stuff, entirely accidentally, but that’s really the only difference.

You consistently demonstrate that, not only have you gained quite a lot of knowledge, but you’re willing to share that to benefit others. You are curious about many different aspects of the web world, and that will carry you far.

Your comments are always well worth listening to, your advice is well-considered and thoughtful, and you know your stuff. I enjoy reading what you have to say, it gets me thinking. :wink:

I love the community forming here at FCC, also the FCC-related chats on Discord and on Slack. The community is vibrant and growing, day by day. The way I see it, when we all start moving into the professional world (or moving UP in the professional world), this will be a GREAT start to a professional network.

As I’ve said repeatedly, @husseyexplores, it ain’t what you know, it’s knowing how to RESEARCH what you don’t know. I find that I google (or MDN lookup) the simplest things, over and over. I know the return value for most of the Array functions (.map() vs .reduce() vs .splice() etc), but I re-check myself multiple times throughout the day, because it’s there.

You got this. And @imendieta, you’re doing great. You’re taking advice, listening to it, and extending your own knowledge by how you advance from that point. Keep up the good work! :wink:

1 Like

There’s a ton of things I would suggest changing on your code.

  1. Readability (by using code format, creating functions that do tasks, using meaningful variable names)
  2. Code format (line up your code properly, be consistent in spacing of code)
  3. Avoid using font-awesome (too slow to load)
  4. Avoid global css selectors

Are just a few without really looking at your logic of code.

Thank you for the kind words!

Believe it or not, when I did few HTML/CSS challenges here on FCC, I also read some forum threads too. I remember someone asked a JS algorithm related question and you wrote a very nice pseudo code explaining what and how it needed to be solved.

My JS skills were not good at that time, so I was just wondering how could I even get there, so I can also start solving some algo related stuff on my own. (And then afterwards, I started with The Odin Project and did a course on Algorithms), so basically, props to you! I got inspired.

You hit the nail on the head there. Who doesn’t look up MDN or stackoverflow at least once in a day, haha!

Is there any slack or discord channels for FCC? I don’t know about them.

And yes, one reason me being here is to pay it forward, second is to network. I have literally zero connections :smile: lol

There was a great conversation here about the discord group (which is at https://discordapp.com/invite/QKCkFkk), if you search FCC for ‘Newbies Discord’ you’ll find the conversation.

And we had set up a Slack workspace some time ago, but that ended up going nowhere. PM me your email, I’ll send invites to it. I can’t figure out how to make the slack open-invitation, if I could I’d just post that. sigh.

<!doctype html>
<html>
<head><title></title></head>
<body>
    <div id="site_container">
      <a href="#" name="add"><span class="plus"></span>Add</a>
      <ul id="menu">
        <li class="item">
          <div class="item_container">
            <input type="text" placeholder="Hello World">
            <a href="#" name="remove"><span class="minus"></span></a>
        </li>
      </ul>
    </div>
<style>

* {
    box-sizing: border-box;
}

#site_container {
    margin: 0;
    padding: 0;
    padding: 20px;
}

#menu {
    padding: 0;
    margin: 0;
    list-style: none;
    margin-top: 20px;
    padding: 10px;
    border: 1px solid #dddd;
}

#site_container a {
    text-decoration: none;
}

#site_container a[name='add'] {
    position: relative;
    color: #fff;
    background: #4992da;
    padding: 8px 20px;
}

#site_container a[name='add'] .plus {
    padding-left: 10px;
}

/* plus sign */
#site_container .plus::before {
    content: "";
    position: absolute;
    top: 16px;
    left: 10px;
    width: 10px;
    border: 1px solid;
    transform: rotate(90deg);
}

#site_container .plus::after {
    content: "";
    position: absolute;
    top: 16px;
    left: 10px;
    width: 10px;
    border: 1px solid;
}

#menu .item {
    padding-bottom: 10px;
}

/* prevents last item to have too much spacing */
#menu .item:last-child {
    padding-bottom: 0;
}

#menu .item input {
    padding: 10px;
    background: #eee;
    border: 1px solid #ddd;
}

.item_container {
    display: flex;
    justify-content: space-between;
}

.item_container a {
    display: block;
    padding: 10px;
    background: #e54f74;
    width: 35px;
}

#site_container .minus {
    position: relative;
}

/* minus sign */
#site_container .minus::before {
    content: "";
    position: absolute;
    top: 7px;
    left: 2px;
    width: 10px;
    border: 1px solid;
    color: #fff;
}
</style>

<script>
(function(){

document.addEventListener("DOMContentLoaded", function(){

    const site_container = document.getElementById("site_container");
    const add_btn = site_container.querySelector("a[name='add']");
    const menu = site_container.querySelector("#menu");

    // enables the first button to be removed
    addRemoveListener(menu.querySelector("a[name='remove']"));

    add_btn.addEventListener("click", function(){
        const menu_item = menu.querySelector("li");

        // creates clone of li and its children
        let clone = menu_item.cloneNode(true);

        // clears out value of new cloned item
        clone.querySelector("input").value = "";

        // adds clone item to menu
        menu.appendChild(clone);

        // enables the remove button to work for each new clone
        addRemoveListener(clone.querySelector("a[name='remove']"));
    });

    function addRemoveListener(btn){
        btn.addEventListener("click", function(e){
            e.preventDefault();

            // prevents all items from being deleted
            if (menu.querySelectorAll("li").length === 1){
                return;
            }

            if (!confirm("Are you sure you want to delete this?")){
                return;
            }
            this.closest(".item").remove();
        });
    }

});

})();
</script>

</body>
</html>

Thank you so much for this amazing resume and experience, @husseyexplores this will help me also get into the having of keep learning and to follow from you and other friends here at the forum to keep learning and find resources like you did before. Im very interesting on the Odin Project looking forward to learn as much as i can to get lots of experience like you do. Thank you so much for sharing your knowledge and experience. Looking to get all this great knowledge from friends like you, and to improve my skills as i go into programming with vanilla JS. Im very grateful for meeting new people with great knowledge, and i will keep learning more and more. This will inspired me to learn more each they, just like @husseyexplores experience with @snowmonkey did,

Thank you so much and we are here to all help each other… :slight_smile:

3 Likes

Looking forward we have a great conversation/discussion regarding this and many topics and thanks for sharing the link @snowmonkey looking forward to have many more… maybe we can use some of that workspace.

Hello there @kerafyrm02 thank you for sharing a wonderful code of the input field. Its very interesting how it is done with a different style. its good to have different flavors, and thank you again for the advice. Thank you.

No problem., I’m glad I could help. Good luck.