nlstduio
nlstduio

Reputation: 51

About getElementById find multiple id name?

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

Upvotes: 3

Views: 146

Answers (5)

Andrew Plummer
Andrew Plummer

Reputation: 1170

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

Upvotes: 1

Andrea Ligios
Andrea Ligios

Reputation: 50261

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.

Upvotes: 0

Shelly
Shelly

Reputation: 351

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/

Upvotes: 0

Dipali Vasani
Dipali Vasani

Reputation: 2536

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>

Upvotes: 0

Manwal
Manwal

Reputation: 23836

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

Upvotes: 4

Related Questions