2

I am fairly new to Jquery and CSS/Html. I have a CSS tree structure and I want to add more Children to the parent when an outside button is click. Can you guys help please?

$(document).ready(function(){
$('a').on('click',function(){
$('a').not(this).removeClass('highlighted');
$(this).toggleClass('highlighted');
if ($('a').hasClass('highlighted')){
$('.btn').prop('disabled', false); 
}
else {$('.btn').prop('disabled', true); } 
});

$('.btn').click(function(){
    var new1 = "<li><a href='#'>AAA</a></li>"
    var new2 = $('.highlighted').children().append(new1);   
})
});

These are what I wrote. Basically I am highlighting the 'li' I am clicking. And try to append a new children 'li' after my current li.

Jimmy W
  • 77
  • 2
  • 8
  • `.append()` but I prefer raw-js for that. https://stackoverflow.com/questions/10619445/the-preferred-way-of-creating-a-new-element-with-jquery – admcfajn Jun 23 '17 at 02:18

2 Answers2

0

You can just do it just like this:

$('.btn').on('click', function(){
   var new1 = "<li><a href='#'>AAA</a></li>"
   var new2 = $('.highlighted').append(new1);   
});

Hope it will help.

0

Try This:

$(document).ready(function(){
  $('a').click(function(){
    $(this).toggleClass('highlighted');
    $('a').not(this).removeClass('highlighted');
    if($('a').hasClass('highlighted')) 
      $('.btn').prop('disabled',false);
    else
      $('.btn').prop('disabled',true);    
  })
  $('.btn').click(function(){
    $('.highlighted').append("<li><a href='#'>AAA(children)</a></li>");
  })
})
.highlighted {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul>
  <li><a href="#">I am Link 1</a></li>
  <li><a href="#">I am Link 2</a></li>
</ul>
<button class="btn" disabled="disabled">ADD</button>
Ehsan
  • 12,655
  • 3
  • 25
  • 44