Turning this vanilla JS

Tags: ,



I am looking to create this in vanilla JS, granted jQuery was used. I wanted to use lean JS. The code below just gave quick results fast. However for build, I would like it leaner.

Several annoying factors, multiple child descendants, unknown classes all and have to be inside a loop.

$('.nav__adv').each(function(){

	var $el = $(this),
		$no_advert = $('.main_ad_container div a div div', $el);

	$el.filter(function() {
	    return $.trim($no_advert.text()) === "Advertise Here";
	}).css("display", "none").remove();

});

Any direction / help / guidance?

Answer

Using plain Javascript. Note that the advantage to using jQuery is that it will work cross browser.

[].forEach.call(document.querySelectorAll(".nav__adv"), function(el) {
    var no_advert = el.querySelector(".main_ad_container div a div div");
    if(no_advert && no_advert.textContent.trim() === "Advertise Here") {
        el.parentElement.removeChild(el);
    }
});
<div class="nav__adv">
    <div class="main_ad_container">
        <div>
            <a>
                <div>
                    <div>Advertise Here</div>
                </div>
            </a>
        </div>
    </div>
</div>
<div class="nav__adv">
    <div class="main_ad_container">
        <div>
            <a>
                <div>
                    <div>Leave Untouched</div>
                </div>
            </a>
        </div>
    </div>
</div>

If you want cross-browser support in vanilla JS, this gets slightly more complicated.



Source: stackoverflow