简体   繁体   中英

Javascript Selecting child element not working

im working on adding a FB share button to all my posts.

so i wanted to use the sharer.php? method with all the parameter retrieved from the post.

So my blog structure

<div id='postwrapper'>
    <div id='title'>
        hello</a>
    </div>
    <div id='da'>
        <span>Posted on </span>
        <span class='divider'></span>
        <span>By</span>
    </div>
    <div class='post_content'>$row['post'] gud day</div>
    <div id='post_footer'>
        <a href=viewpost.php>Continue reading</a>
        <a href='#' onClick='fbshare(this)'>Insert text or an image here.</a>
    </div>
</div>

My javascript for fbshare function (not complete).

function fbshare(fb) {
    var p1 = fb.parentNode;
    var p2 = p1.parentNode;       
    var title = p2.getElementById("title").innerHTML;        
    alert(title);
}

Everytime i try this it says undefined is not a function

getElementById is a function of the document . Assuming you have more than one post on the page ( id s must by unique), try using a class instead:

<div class='title'>

And using getElementsByClassName :

var title = p2.getElementsByClassName("title")[0].innerHTML;

http://jsfiddle.net/AJ9uj/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM