0

I have the following fiddle.

When you click the Hide button the numbers 2, 3 and 1 are hidden. All works great using this Jquery code:

$( "#hide" ).click(function() {
   $('span').each(function(){
   if($(this).text().match(/^([1-9])$/))$(this).hide()
});

});

Now I want the same thing, but with using a good old javascript function instead of the jQuery solution given above. How to do this? See my (not working) attempt here.

Many thanks

3
  • 1
    wrap code in head .It works --> jsfiddle.net/cse_tushar/WnLUu/5 Commented Oct 27, 2013 at 13:12
  • @TusharGupta There's still jQuery in that code. $('span').each(function () { Commented Oct 27, 2013 at 13:15
  • @VilleRouhiainen I know that.That's why i posted it as comment not as an answer . Commented Oct 27, 2013 at 13:16

4 Answers 4

2

Here is a simple vanilla JS version:

function hide() {
    var spans = document.getElementsByTagName('span'), i = 0;
    for(i=0; i<spans.length; i++) {
        spans[i].style.display = (spans[i].innerText.match(/^[1-9]+$/) ? 'none' : '');
    }
}

Note: I've corrected your regex to match numbers with more than 1 digit in it.

Updated fiddle: http://jsfiddle.net/WnLUu/6/

Sign up to request clarification or add additional context in comments.

3 Comments

.innertText is not available on all browsers, if .innerText === undefined you should use .textContent instead.
Thanks! Just out of curiosity, how would I make them visible again if I had another button called: Show? With Jquery you can simply use show.
With vanilla Js, you can just as easily do: yourSpan.style.display = 'inline';
0

In plain javascript you could access the style attribute, so instead of $(this).hide() you could call

this.style.visibility = "hidden"

Comments

0

Maybe something like this.

function buttonClicked(evt) {
    var spans = document.getElementsByTagName("span");
    for (var i = 0, length = spans.length; i < length; ++i) {
        if (/^([1-9])$/.test(spans[i].innerHTML)) {
             spans[i].style.display = "none";
        }
    }
};


document.getElementById("hide").addEventListener("click", buttonClicked, false);

Comments

0

Please try this (works on IE and other browsers, .innerText is IE specific):

function hide() {
    var spans = document.getElementsByTagName('SPAN');

    for (var i=0; i < spans.length; i++) {
        alert(spans[i].textContent);
        if (spans[i].textContent !== undefined && spans[i].textContent.match(/^[1-9]$/))
            spans[i].style.display = 'none';
        else if (spans[i].innerText !== undefined && spans[i].innerText.match(/^[1-9]$/)) // IE
            spans[i].style.display = 'none';
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.