www.webdeveloper.com
Results 1 to 4 of 4

Thread: Help needed for my very simple script (or so I assumed)

  1. #1
    Join Date
    Aug 2013
    Posts
    2

    Question Help needed for my very simple script (or so I assumed)

    Hello guys,

    Sorry to bother you with such a trivial issue, fact is, I'm not really into JS, don't use it often, and now I'm really stuck trying to make work a rather simple script... can someone help me please ?


    I want to locate a span by its class name, then get to the div (no id, no class) inside of it, and change the div contents, and I have been ridiculously failing at it for hours now.

    Here is the HTML part :

    HTML Code:
    <span class="myClass"><--! Some commented text --><div>many HTML tags and text in here</div>other content I don't want to change</span>
    And my useless script... :

    Code:
    var parents = document.getElementsByClassName('myClass'); // length return 3
    var span = parents.firstChild;
    var div = span.getElementsByTagName('div'); // should return only 1
    var divToUpdate = div.firstChild;
    divToUpdate.innerHTML="changed content";

    Can someone see where the problem is ?

    Thanks,

    Kelly

  2. #2
    Join Date
    Jun 2008
    Posts
    106
    getElementsByClassName returns an HTML Collection which is similar to an array. You can't just use .firstChild on it; it needs to be an element first to do that, not a list/collection.

    I'd suggest going with querySelector, if it's supported by your browser:
    Code:
    var divToUpdate = document.querySelector('.myClass > div');
    divToUpdate.innerHTML = "changed content";
    Or, if it's not:
    Code:
    var divToUpdate = document.getElementsByClassName('myClass')[0].getElementsByTagName('div')[0];
    divToUpdate.innerHTML = "changed content";
    You said there were 3 "myClass"es so hopefully you get the correct one.
    Last edited by tenfold; 08-14-2013 at 04:53 AM.

  3. #3
    Join Date
    Aug 2013
    Posts
    2
    Oh, you're good ! that was just it, thank you so much, it works perfectly now !
    I'm really grateful for your help

  4. #4
    Join Date
    Jun 2008
    Posts
    106
    You're welcome

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles