Becky
Becky

Reputation: 5585

Access an element inside a div

When the div structure is

<div><svg id="apple"></svg></div>

I use the below to access the svg file.

document.getElementById('apple').parentNode.innerHTML

My question is, how do I access the svg when the div structure is as below.

<div id="apple"><svg></svg></div>

Upvotes: 2

Views: 8823

Answers (5)

Kalpesh Panchal
Kalpesh Panchal

Reputation: 985

This is pretty standard practice in JavaScript.

To select all <svg> elements use:

var svgs=document.getElementsByTagName('svg');

To select the first <svg> element within <div id="apple">

var x=document.getElementById('apple').getElementsByTagName('svg')[0];

Note: getElementsByTagName() returns an array of elements and [0] selects first out of them.

Upvotes: 1

FlokiTheFisherman
FlokiTheFisherman

Reputation: 234

You can access this way.

  <div id="apple"><svg></svg></div>

    <script>

        var svg = document.getElementById('apple').firstChild // with this you reference the svg tag.

    </script>

Upvotes: 0

Bryan Mudge
Bryan Mudge

Reputation: 432

Try:

var mySvg = $('#apple').children('svg');

Upvotes: 0

Thomas Stringer
Thomas Stringer

Reputation: 5862

$("#apple").children("svg")

This will get you the svg children of your apple div.

If you just want the first match, you'd do this:

$("#apple").children("svg").first()

Here's a jsfiddle showing how this can be used: https://jsfiddle.net/o7xyrbbL/

Upvotes: 0

Tatarin
Tatarin

Reputation: 1298

In jquery you would do this:

$("#apple svg")

In Javascript you would do this

document.getElementById('apple').innerHTML

Upvotes: 6

Related Questions