0

What I have with jQuery:

if ($('#vote_c').length > 0) {
    $('#vote_button').show().click();
}

I am trying to re-write it so it uses raw javascript:

if (document.getElementById('vote_c').length > 0) {
    // what goes here
}
3
  • 2
    document.getElementById('vote_c').length id is unique, so this function selects only one single element, no need in .length. Commented Nov 17, 2014 at 18:45
  • @Cheery Not only that, but length will be undefined. Commented Nov 17, 2014 at 18:45
  • (ID bla bla) also, have you tried document.dispatchEvent(event); ? Commented Nov 17, 2014 at 18:45

3 Answers 3

1
// cache lookup
var vote = document.getElementById('vote_c');
// using truthy/falsy value to determine existence
// proper test would be (vote !== null)
if (vote) {
    // this is probably closest to what .show() does
    // .show actually seems to track what the initial
    // computed display state for the element was and
    // along with .hide, toggles between the initial
    // state and 'none'.
    vote.style.display = '';
    // mimicking .click() is done any number of ways
    // but the easiest is below:
    vote.onclick(); // call any registered handlers for the click event;
    //
    // OR (second easiest way) you could define a click event:
    //
    var event = new MouseEvent('click', {
        "view": window,
        "bubbles": true,
        "cancelable": true
    });
    // and then "dispatch" that event to the targeted
    // element which should trigger the handlers
    vote.dispatchEvent(event);
}
Sign up to request clarification or add additional context in comments.

Comments

1
if (document.getElementById('vote_c')) {
    var btn = document.getElementById('vote_button');
    btn.style.display = "inline"; //show
    btn.click() //click
}

Comments

1
document.getElementById('vote_button').onclick = function(){
    document.getElementById('vote_button').style.display = 'block';
};

Oh, my bad. I did not see the if statement, but it should point you in the right direction.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.