Issac Issac - 3 years ago 68
CSS Question

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: Fiddle

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;
}

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download