How do I choose the value of a select that does not have an identifier but its div?

2

I'm using the Chrome console to try this because I would use it as a script to save time on a task I do.

The idea is this, I have this

<div id="seccion1">
    <select>
       <option value=1>Ejemplo 1</option>
       <option value=2>Ejemplo 2</option>
    </select>
</div>

<div id="seccion2">
    <select>
       <option value=1>Ejemplo 1</option>
       <option value=2>Ejemplo 2</option>
    </select>
</div>

Then I want the section select1, when the app is loaded, from the browser and with the console to set the value of the select, the issue is that as it does not have its own ID, I can not use the getElementById, not really I know how to do. Any ideas?

    
asked by Carlos 03.02.2017 в 01:58
source

3 answers

6

Use the QuerySelector method.

Example: document.querySelector("#seccion1 > select").value=1

Gets the first "select" element in the document where his father has the id "section1".

    
answered by 03.02.2017 в 02:23
4

With jquery you can do it like this:

var select = $("#seccion1 select");

Review the example:

var select = $("#seccion1 select");

alert(select.text());

//Una vez que tenga el objeto ya puedes hacerle las modificaciones que desees:

$(select).css('width','250px');
$(select).css('height','30px');
$(select).css('color','blue');
$(select).append('<option value=3>Ejemplo 1.3-Agregado</option>');
$(select).append('<option value=4>Ejemplo 1.4-Agregado</option>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="seccion1">
    <select>
       <option value=1>Ejemplo 1.1</option>
       <option value=2>Ejemplo 1.2</option>
    </select>
</div>

<div id="seccion2">
    <select>
       <option value=1>Ejemplo 1</option>
       <option value=2>Ejemplo 2</option>
    </select>
</div>

Checked if you accept jquery Chrome :

This version is the one I'm using:

    
answered by 03.02.2017 в 02:17
1

var x=document.querySelector("#seccion1 > select");
console.log(x);
<div id="seccion1">
    <select>
       <option value=1>Ejemplo 1</option>
       <option value=2>Ejemplo 2</option>
    </select>
</div>

<div id="seccion2">
    <select>
       <option value=1>Ejemplo 1</option>
       <option value=2>Ejemplo 2</option>
    </select>
</div>
    
answered by 03.02.2017 в 03:32