简体   繁体   中英

Assign a variable for nested element

How do I assign a variable for the svg inside the div with an ID of parent1 in javascript?

structure

<div id="parent1">
   <svg.....></svg>
</div>

js

var target = document.getElementById("parent1").svg;

这应该工作:

var target = document.querySelector('#parent1 svg');

You can use document.querySelector to find elements by CSS selector .

For an svg element inside of an element with id parent1 , it would be

var target = document.querySelector('#parent1 svg');

As shown in the comments, there is a few answers to this.

  1. you can query an element for children, grandchildren, etc.
var target = document.getElementById("parent1").querySelector('svg')
  1. grabs first svg under the #parent in the heirarchy (melpomene's answer)
var target = document.querySelector('#parent1 svg');
  1. grabs only a direct child svg in #parent (j08691's answer)
var target = document.querySelector('#parent1 > svg')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM