I have this simple jQuery snippet (very simple with jQuery) and I want to convert this to javascript which seems to be really hard.
For example, I have no idea what to do with the .each – function.
Hope you can help, give me a hint or solve the problem quickly.
$("#rTab div[id^=tab]").each(function(){
if( !$.trim( $(this).html() ).length ) {
id = $(this).attr("id");
//alert(id);
$("#rTab li[rel="+id+"]").hide();
}
});
$(".tabContent").hide();
$(".tabContent:first").show();
//click MUSS live
$("ul.tabs li").live('click',function() {
$("ul.tabs li").removeClass("active");
$(this).addClass("active");
$(".tabContent").hide();
//MUSS rel, weil href mit location.hash in product.php so nicht läuft
var activeTab = $(this).attr("rel");
$("#"+activeTab).fadeIn();
});
Here you go:
It’s more code, yes. The problem is that all those jQuery selectors can return multiple elements, so it’s a loop for every selector. Hence the alias to make that slightly shorter.
At least this should give you an idea of how things work in native JS. Please note that the
querySelectorAllisn’t supported on older browsers, andforEachis IE 9+.Also, in the
.style.display = 'none';and.style.display = 'block';, you may want to cache the old display value somehow, since not all elements useblockas default display setting.An alternative to