Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

contentDocument in jQuery

I have the following js script to access elements inside a object (SVG - <object data="bbbbbb.svg" type="image/svg+xml" id="alphasvg" width="100%" height="100%"></object> )

jQuery(document).ready(function($) {

    $(window).load(function () {


        var a = document.getElementById("alphasvg");
        var svgDoc = a.contentDocument; 
        var delta = svgDoc.getElementsByTagName("path");    
        $(delta).click(function() {

            //do stuff

        })

    });
});

I want to use jQuery to access the elements and tags. I'm completely stuck on the contentDocument part. How can I convert this to jQuery so I can use attr etc?

I want to be able to access and modify attributes in jQuery instead of having to use the traditional js methods which I am unfamiliar with.

How someone can help me?

Thanks a million.

like image 399
user752135 Avatar asked May 13 '11 10:05

user752135


People also ask

What is contentDocument?

The contentDocument property returns the Document object generated by a frame or iframe element. This property can be used in the host window to access the Document object that belongs to a frame or iframe element.

How is content manipulation done in jQuery?

Three simple, but useful, jQuery methods for DOM manipulation are: text() - Sets or returns the text content of selected elements. html() - Sets or returns the content of selected elements (including HTML markup) val() - Sets or returns the value of form fields.

How use contains in jQuery?

The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).

Can you access the content of an iframe?

You could use . contents() method of jQuery. The . contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.


2 Answers

You should be able to access the paths directly like elements, no need for contentDocument or getElementsByTagName, etc:

jQuery(document).ready(function($) {

    $(window).load(function () {

        $("#alphasvg path").click(function() {

            //do stuff
            // $(this).attr('d') = the path

        })

    });
});
like image 140
Gary Green Avatar answered Oct 22 '22 22:10

Gary Green


Like this:

$(svgDoc).find("whatever").doWhatever();

Demo here and code here. Note that I've used an <iframe> for demonstration hence the first URL will work, second will give you "permission denied" error if you try to run the fiddle.

like image 5
Salman A Avatar answered Oct 22 '22 23:10

Salman A