How to search by class (instead of id) in Javascript/jQuery

Asked

Viewed 1,263 times

4

I’m using a plugin for popular city/state, but I wanted to use in more than one select, so I wanted to use per class instead of ID, but what I tried so far didn’t work.

I tried to follow this famous Soen question, but it didn’t work in the script I’m using:

<script>
        window.onload = function() {

            new dgCidadesEstados({
                estado: document.getElementById('estado'),
                cidade: document.getElementById('cidade'),
                estadoVal: '<%=Request("estado") %>',
                cidadeVal: '<%=Request("cidade") %>'
            });
        }
    </script>

With id he works right, as you can see in this question, but I tried so for example { estado: document.getElementById('estrec').className = "estado", and putting the class in the select, but it didn’t work out.

Follows a FIDDLE that @Sergio posted in this answer (is with only two states).

2 answers

5


Since this plugin expects one element at a time you can replace the getElementById for querySelector not taking into account that you should use . for class and # for ID.

So the same example with classes would be:

new dgCidadesEstados({
    estado: document.querySelector('.estado'),
    cidade: document.querySelector('.cidade'),
    estadoVal: '<%=Request("estado") %>',
    cidadeVal: '<%=Request("cidade") %>'
});

jsFiddle: http://jsfiddle.net/w938st7q/1/

If you want to apply this plugin to many selects just have a loop that passes elements one by one.

For example, for this HTML:

<form id="sistema" name="sistema" method="post" action="">
    <div>
        <label>Estado</label>
        <select class="estado" name="estado"></select>
        <label>Cidade</label>
        <select class="cidade" name="cidade"></select>
    </div>
    <div>
        <label>Estado</label>
        <select class="estado" name="estado"></select>
        <label>Cidade</label>
        <select class="cidade" name="cidade"></select>
    </div>
</form>

you can use it like this:

window.onload = function () {
    var divs = document.querySelectorAll('form > div');
    for (var i = 0; i < divs.length; i++) {
        new dgCidadesEstados({
            estado: divs[i].querySelector('.estado'),
            cidade: divs[i].querySelector('.cidade'),
            estadoVal: '<%=Request("estado") %>',
            cidadeVal: '<%=Request("cidade") %>'
        });
    }
}

jdFiddle: http://jsfiddle.net/w938st7q/2/

  • Hi Sergio, thanks again! I made a test here taking only the HTML referent of my page and works beauty, but when I put in the rest of my Html does not work... I think it has to do with the loop of the elements, because, for example, I include an extra empty div in the fiddle that you posted, It no longer works... In my HTML it has many elements before these... the manure is container type > Row > form > col > Row > col (city/state) > Row > col > Row > col (city/state) etc... I need to inform all this structure in the var divs?

  • @gustavox puts the HTML you have around the elements that have select that I can take a look at and explain how to use.

  • So, HTML is pretty big to post whole, but I created one fiddle reproducing the structure. The error that appears in the browser debug is Uncaught TypeError: Cannot read property 'length' of undefined.

  • I already marked as solved and gave +1 because in thesis already solved, but I still need your help to adapt to the structure of my HTML... ;)

  • So I was testing, and in the example of the fiddle structure I passed it worked like this: var divs = document.querySelectorAll('div > div > div > div'); but I don’t think I’ve passed the correct structure because in my HTML it hasn’t even worked :/, but I think I’ve got the concept, to look here, will work :-)...

  • So this way it worked, but when I put the flat-ui class (getting like this: <select class="select select-primary select-exemploa cidade" name="Tcid" id="Ccid" data-toggle="select">) that using in select, it pops and appear the options outside select, and select does not appear... but I think this is another question right... :/

  • @gustavox by fiddle HTML above you can use '#Cpost .classdivcol' -> http://jsfiddle.net/uzqf15mn/2/

  • Sets the HTML of this "flat-ui class" to see what is

Show 4 more comments

1

You can do this using jquery:


$(document).ready(function() {
 var elementoDaClasse = $(".nomeDaSuaClasse");
});

or use javascript without dependency in this way:

var elementoDaClasse = document.getElementsByClassName("nomeDaSuaClasse");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.