Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the wrapper `div` from the whole `h1 - h6` tag and only wrap the current one

I'm trying to remove the wrapper <div class="headWrap"> from the whole h1 - h6 tag and I need only wrap the current heading tag when I click on this.

Here is the link: https://jsfiddle.net/q8yhoxhd/4/

HTML:

<h1>
    Heading Test content 1
</h1>
<h2>
    Heading Test content 2
</h2>
<h3>
    Heading Test content 3
</h3>

JS

$(function(){
    $(document).on('click', function(event){
        var clickedTag;
            clickedtag = event.target;
      event.stopPropagation();
      var headings = $('h1, h2, h3, h4, h5, h6');
      if($(clickedtag == headings)){
      $(clickedtag).wrap($('<div/>').addClass('headWrap'));
      }
  });
});

CSS

.headWrap {
  background-color:red;
  color:#fff;
}
like image 360
Devbuddy Avatar asked Dec 09 '25 13:12

Devbuddy


1 Answers

You need 2 things.

  1. Include jQuery

  2. unwrap all other headers and wrap only the clicked header.

This is the same code from the fiddle. All I did is

Added jQuery library

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

added code to unwrap all headers on each click event.

$(headings).unwrap();

$(document).ready(function(){
$(document).on('click', function(event){
  		var clickedTag;
			clickedtag = event.target;
      event.stopPropagation();
      var headings = $('h1, h2, h3, h4, h5, h6');
      $(headings).unwrap();
      if($(clickedtag).is(headings)){
      $(clickedtag).wrap($('<div/>').addClass('headWrap'));
      }
  });
  });
.headWrap {
  background-color:red;
  color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
Heading Test content 1
</h1>
<h2>
Heading Test content 2
</h2>
<h3>
Heading Test content 3
</h3>
<p>Test</p>

Thanks to gaetanoM. I missed that point. You can't simply use ==. use jQuery .is() instead to check similarity.

like image 113
Sagar V Avatar answered Dec 11 '25 02:12

Sagar V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!