选择子节点(DOM)

时间:2015-09-29 18:33:34

标签: javascript dom child-nodes

如何使用纯Javascript选择第二个<div class="navigation"> <a href="/page/2/">Prev</a> <a href="/page/4/">Next</a> </div> 标记?

public class EnterActivity extends Activity implements SurfaceHolder.Callback` 

    private MediaPlayer mp = null;
    SurfaceView mSurfaceView=null;

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);

        mp = new MediaPlayer();
        mSurfaceView = (SurfaceView) findViewById(R.id.video_surface);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        Uri video = Uri.parse("android.resource://" + getPackageName() + "/"
                + R.raw.video);

        mp.setDataSource(video);
        try {
            mp.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Get the dimensions of the video
        int videoWidth = mp.getVideoWidth();
        int videoHeight = mp.getVideoHeight();

        //Get the width of the screen
        int screenWidth = getWindowManager().getDefaultDisplay().getWidth();

        //Get the SurfaceView layout parameters
        android.view.ViewGroup.LayoutParams lp = mSurfaceView.getLayoutParams();

        //Set the width of the SurfaceView to the width of the screen
        lp.width = screenWidth;

        //Set the height of the SurfaceView to match the aspect ratio of the video
        //be sure to cast these as floats otherwise the calculation will likely be 0
        lp.height = (int) (((float)videoHeight / (float)videoWidth) * (float)screenWidth);

        //Commit the layout parameters
        mSurfaceView.setLayoutParams(lp);

        //Start video
        mp.start();

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }
}

1 个答案:

答案 0 :(得分:2)

使用DOM选择器getElementsByClassName()

返回值: 包含类名的元素数组。

[?]替换为getElementsByClassName选择器的返回值中的目标索引。例如,如果包含<div>标记的<a>标记是具有类名navigation的文档的第一个元素,那么它将位于索引0(因为它是因此,您应该使用[0]作为相应的元素。

使用.children属性返回其父节点(在本例中为<a>标记的HTMLCollection子节点(在本例中为<div>标记) )。

// JS

document.getElementsByClassName('navigation')[1].children[1];

// HTML

<div class="navigation">
    <a href="/page/1/">Prev</a>
    <a href="/page/2/">Next</a> 
</div>
<div class="navigation">
    <a href="/page/3/">Prev</a>
    <a href="/page/4/">Next</a> (selected element)
</div>
<div class="navigation">
    <a href="/page/5/">Prev</a>
    <a href="/page/6/">Next</a> 
</div>
<div class="navigation">
    <a href="/page/7/">Prev</a>
    <a href="/page/8/">Next</a> 
</div>