0

How do I access an element inside the header.html file, loaded in the javascript code, using document.getElementById("element") inside the index.js? There is another way of accessing it from the index.js file?

index.html file

<html>
<head>
    <meta charset="utf-8">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <link rel="stylesheet" type="text/css" href="css/style.css"/>
    <script src="js/jquery.js" type="text/javascript"></script>
    <script>
        $(function(){
            $("#header").load("header.html");
            $("#footer").load("footer.html");
        });
    </script>
    <script src="https://www.gstatic.com/firebasejs/3.9.0/firebase.js"></script>
    <script src="js/app.js" type="text/javascript" language="javascript"></script>
    <script src="js/index.js" type="text/javascript" language="javascript" defer></script>
</head>
</html>
IronBoy
  • 39
  • 8
  • You wouldn't put a `#` symbol in your ID selector when using `getElementById`, so simply removing it could work. But since you're using jQuery anyway, you could access the elements like `$('#header .element')`, for example, if an element being loaded into the header had the class of `element`. – Jon Uleis May 18 '17 at 21:33
  • Not sure if you want to use jQuery or JavaScript. if you want to use jQuery it's as follows: `$('#someelement').load('header.html #header')`. – Robert Rocha May 18 '17 at 21:36
  • I am trying to get a reference of the object to use it with an **onclick**. – IronBoy May 18 '17 at 21:42

3 Answers3

0

Try this using Jquery:

$.get('header.html', null, function(content){
   alert($(content).find('#element'));
});
Joseph D.
  • 10,071
  • 3
  • 21
  • 54
0

Sounds to me like you would need to wait until $("#header").load("header.html"); is done before trying to do anything with the loaded contents. Perhaps $("#header").load("header.html", onHeaderLoaded); might work (assuming you have a function named onHeaderLoaded defined somewhere, possibly even in index.js)

See jQuery .load() for details on using the complete function.

Mark Priddy
  • 486
  • 7
  • 15
0

You need to load your header.html into an existing element in your page, and then you can do using JQuery:

$( "#existing-element" ).on( "click", "element-from-header-file", function() {
    //do stuff
});

Or you can use body instead, if you don't want to/can not load your header into an existing element:

$( "body" ).on( "click", "element-from-header-file", function() {
    //do stuff
});

You may want to read this.

Przemek K.
  • 75
  • 8