0

I have a html:

<div id="sliderFrame"><div id="slider"></div></div>

I want to insert html code into slider div, and I know

$('#slider').append('<a class="lazyImage" href="sample.jpg"></a>');

will work.

I am wondering if I can achieve this using innerHTML, but I failed to do it because document.getElementById().getElementById() can not work. And I found chaining getElementById , but I don't quite get it, any one has simpler solution or can explain this?

Community
  • 1
  • 1
  • 6
    Why would you even need to chain multiple `getElementById()` calls instead of just calling it once and going straight to the element you want? – BoltClock May 26 '14 at 05:36
  • I don't understand. If you have some working code. Why do you want to change it? Please clarify. – bestprogrammerintheworld May 26 '14 at 05:38
  • 1
    `getElementById()` is a method of the document object. It is NOT a method of individual elements which is why you can't chain it. Also, there should be no reason to chain it because ids are unique in the document and thus you can just do `document.getElementById()` on the end result id and it will be found if it exists. – jfriend00 May 26 '14 at 05:40

3 Answers3

1

is this what you want ?

document.getElementById('slider').innerHTML = '<a class="lazyImage" href="sample.jpg">  
                                               </a>'
schnill
  • 905
  • 1
  • 5
  • 12
0

There can only be one id in a page (see the spec):

7.5.2 Element identifiers: the id and class attributes

Attribute definitions

id = name [CS]

This attribute assigns a name to an element. This name must be unique in a document.

So assuming your document is well-formed, you only need one getElementById().

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

you could do

var slider = document.getElementById("slider");
slider.innerHTML = '<a class="lazyImage" href="sample.jpg"></a>';

but like the comments said, why would you want to do this? What you have is fine.

a2345sooted
  • 569
  • 5
  • 20