Append vs After method confusion

Append vs After method confusion
0

#1
<!DOCTYPE html>
<head>
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
  <body>

    <h1>Course Catelog</h1>
    <h3>Below is a list of course offerings to choose from</h3>

    <div id="course_name">
        <input type="textbox"></input>
    </div>
    <div id="div1" class="div_next">
        <button id="btn_1">Add Course</button>
    </div>
    <div id="statement">
        <h3></h3>
    </div>
    <div>
        <p>Below is a list of all the available courses <br>
        that can be enrolled in this semester:
        </p>
    </div>
    <ul id="courses">
      <li>Sociology</li>
      <li>Psychology</li>
      <li>Mathematics
        <ul id="math_subjects">
        <li>Algebra</li>
        <li>Geometry</li>
        <li>Calculus</li>
        </ul>
      </li>
      <li>Sciences
          <ul id="science_subjects">
          <li>Geology</li>
          <li>Physics</li>
          <li>Chemistry</li>
          </ul>
      </li>
      <li>World History</li>
    </ul>

        <script src="js/jquery-3.1.1.min.js"></script>
        <script src="js/custom_jquery_code.js"></script>

  </body>
</html>
----------------------------------------------------------------------------------------------------
.div_next {
    display: inline-block;
}

-----------------------------------------------------------------------------------------------------
$(function(){

       var $inputval;
	$("#div1 > #btn_1").on("click",function(){

		$inputval=$("#course_name > input").val();
		$("#statement > h3").text("Course Entered: "+$inputval).css("background-color","green");        
	});
    
    $("#courses").find("li").on("click",function(e){
            
        var $inputli=$("<li>"+$inputval+"</li>");
        $inputli.css({"background-color":"yellow"});
    	$(this).after($inputli);
        e.stopPropagation();  
    });

});

Hello campers !!. I am having a difficluty in understanding the difference between append and after methods of jquery. This is a small program in which after clicking every “li” element there should appear a “li” of input text which will be with a background of yellow. The input text will have background of green color after clicking “addcourse” button. The problem is with the behaviour of append and after. If I use append it works fine. Clicking every “li” will give us another “li” of added course preceded by clicked “li”. If I use after method what happen is if for example I input text of “My Course” than I clicked “Sociology”, a “li” will be added after it. But if I again click newly added li “My Course”, no “li” is again adding up after the clicked “li”. And if I click a “li” in nested “ul” for example “Algebra” I will have the added “li” of “My Course” right after “Algebra”, and this time if I click the newly added “li” i.e "My Course, a “li” will be added but not right after the clicked “li” but AFTER the whole nested “ul” which is “Mathematics”…The motive is whenever we click any “li” there should be a “li” added right after it with background color “yellow”. Just replace the after method with append if u wanna know how the program should work.


#2

If append does what you want, why bother with after?

I found the following explanations for append vs after:

.append(): This function Insert the data or content inside an element at last index. Means it puts the content inside an element (making the content its child) specified by the parameter at the end of element in the set of matched elements.

after(): This function puts the element after the specified element. Or you can say that it insert data outside an element (making the content its sibling) in the set of matched elements.


#3

I know but for my future learning of course. I spent almost 1 hour in tackling this problem. Wasted so much time for not knowing the reason why after is not working right here. I know the basic difference too but if you see the program “after” should also be working but it’s not !!


#4

Is this what you want?

$(function(){
  var $inputval;
	$("#div1 > #btn_1").on("click",function(){
	  $inputval=$("#course_name > input").val();
	  $("#statement > h3").text("Course Entered: "+$inputval).css("background-color","green")   
	});
    
  $("#courses").find("li").on("click",addIt);

  function addIt(e) {
    var $inputli=$("<li>"+$inputval+"</li>");
    $inputli.css({"background-color":"yellow"});
    $inputli.bind("click", addIt);
    $(this).after($inputli);
    e.stopPropagation();  
  }
});

#5

Yes exacty. But why its not working in my case what am I doing wrong in my code.


#6

As new “li” is added if we inspect element in dev tools the new “li” will also be as other “li”’ elements. But clicking the new “li” do nothing. And if the newly added “li” is in nested “ul” element and we click it, it adds “li” but after the “ul” making it sibling of other outermost “ul” 's “li”


#7

They key to learn here is in your original code:

    $("#courses").find("li").on("click",function(e){        
        var $inputli=$("<li>"+$inputval+"</li>");
        $inputli.css({"background-color":"yellow"});
    	$(this).after($inputli);
        e.stopPropagation();  
    });

The above code only runs once, so the click event is attached to existing li elements. With my version, I bind the same click event handler to the $inputli which is then put after the current li element being clicked. Without binding the click event to it at it’s creation, it does not have a click event to make the new li element respond to a click.


#8

Strange. Because in dev tools it appears as other li elements. And click event is on all “li” elements. So if thats the case as you are saying why if we click newly added “li” in nested “ul” elements will trigger the click event even though it is putting the newly added “li” at wrong position. Newly “li” elements in nested “ul” should also be not doing anything according to your logic ?


#9

I was under the impression that the code I created accomplished what you wanted. If so, then I would not say it is in the wrong position. Did I misunderstand you thinking my code accomplished what you were trying to achieve? I thought you were wanting a new li element with yellow background to be insert below (but on the same level) as current li element regardless if it is nested in the sub ul or not.


#10

Yeah this is what I want!! Ok wait Sir if u run my code and just click “Algebra” . What happens is a new element is added under Algebra right ! Now click the newly added element what happens ? It add the newly added element above “Sciences”. You see the problem ?. Run my code follow the steps I said and you will know !! and thanks for taking up your precious time for me :slight_smile:


#11

I understand what your code (using the after function) is doing and why you do not want it to do that. That is why I posted my solution to your problem using the after function.

Using my version (with after) - The page loads and enter Trigonometry into the course input box and click Add Course. I get Course Entered: Trigonometry with a green background. Next, I click Algebra and a new li element with text of Trigonometry and background color of yellow is added directly below the existing Algebra li element. If I click my new Trigonometry li element, I get another li element with text of Trigonometry and background color of yellow added directly below the first Trigonometry li element. My version does not add a new li element above Sciences.

I think we are having a communication failure here, because I believe I have answered your original question plus have given you a way to use the after function to accomplish what you want.


#12

Sir I am getting every bit of your logic. I asked you why my code doesnt works and you told me that “Without binding the click event to it at it’s creation, it does not have a click event to make the new li element respond to a click.” which means newly added li will not have a click event in my code. But if newly li dont have click event on it than why newly “li” in nested “ul” produced a “li” (even if it is producing it in a wrong position). I just wanna know why my code dont works and the reason u gave me contradicts the functionality my code is showing.


#13

I think I understand what you are wanting to know. I am not positive, but I believe it has something to do with the way the find function puts the event handlers on all descendants of the ul with id=“courses”. Maybe since there is no specific binding (like my solution has), the newly created li “inherits” the click event of the parent “Mathematics” and causes a click on the newly created li to put the next li under “Mathematics” / above “Sciences” as that would be the sibling after? Again, I am not 100% sure about this, but I will keep digging and if I come up with a better explanation, I will post it here. If you find a better explanation, definitely let me know.


#14

Yes thats what I think too. In case of “after”,the click event is on all existing li. Now if I click Sociology it creates a li next to it but newly created li will not have click event on it. But if I click any li inside nested ul say Algebra it will create another “li”. But this time newly created “li” will inherit click event from its parent Mathematics.And if I click this newly created li it will create “li” after Mathematics (above Sciences). In case of “append” as every newly created “li” is inside its parent element so it will inherit click event from it and similarly it is appending another newly “li” inside it so it also inherit click event form it and so on…