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;
}
You need 2 things.
Include jQuery
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With