3

I have three id tag

<div id="view_1"></div>
<div id="view_2"></div>
<div id="view_3"></div>

I use getElementsByClassName way it can work

but "class" I take it to delimit css style

How could use document.getElementById find -> "view_1" "view_2" "view_3"

    function hideDIV(){

        var divs = document.getElementById('view'.*);
        for(var i=0; i<divs.length; i++) { 
          divs[i].style.display='none';
        }
    }

enter image description here

Cœur
  • 34,719
  • 24
  • 185
  • 251
nlstduio
  • 51
  • 3

5 Answers5

4

You can do this:

var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++) {
    if(divs[i].id.indexOf('view_') == 0) {
        divs[i].style.display='none';
    }
}

DEMO

Manwal
  • 22,994
  • 11
  • 59
  • 91
1

Use QuerySelectorAll for that:

document.querySelectorAll('[id^="view_"]').id;

This will get all views that start with view_

See: Javascript getElementById base on partial string

Community
  • 1
  • 1
Andrew Plummer
  • 1,150
  • 1
  • 12
  • 21
0

Try doing this : Fiddle

JS:

$('[id*="view"]').hide();

Html:

<div id="view_1"> dcf</div>
<div id="view_2"> DSg</div>
<div id="view_3"> gsde</div>
Dipali Vasani
  • 2,430
  • 2
  • 15
  • 30
0

No, it won't work.

document.getElementById() method accepts only one argument.

However, you may always set classes to the elements and use getElementsByClassName() instead. Another option for modern browsers is to use querySelectorAll()method:

use $("div[id*='view']")

DEMO :http://jsfiddle.net/mkufymqr/1/

Shelly
  • 357
  • 1
  • 7
  • thanks everyone , Excuse me, if I would add variable in here function hideDIV(idTag){ $('[id*='+idTag+'"_"]').hide(); Is this right way ? – nlstduio Apr 17 '15 at 07:27
0

Vanilla JavaScript

document.querySelectorAll('div[id^="view_"]');

jQuery

$('div[id^="view_"]');

CSS 3

div[id^="view_"] { ... }

But consider using classes, not IDs, to semantically target elements.

Eg: search for all DIVs with the targetDiv class, and add the hidden class to them. Then define the hidden class as display: none in CSS.

Andrea Ligios
  • 47,982
  • 25
  • 109
  • 228