2

Say I have an element <a href="/foo#bookmark">. I want to reference this element by its hash, which I can do using jQuery. How would I do this only using JavaScript?

Example code:

<a id="foo" href="/foo#bookmark" onclick="exampleFunction(this)">Some text</a>

<script>
/**
 * @param {Element} el
 */
function exampleFunction(el) {
    let bookmarkHash = el.hash,
        $bookmarkElement = jQuery(bookmarkHash);

    console.info($bookmarkElement.offset().top);
}
</script>

Here jQuery(bookmarkHash) references the original <a> so I can get the offset of the element. How can I do this in pure JavaScript?

3
  • 1
    You're passing in the element to the fuction, just use $bookmarkElement = $(el); Commented Sep 9, 2016 at 19:53
  • I don't want to use jQuery at all. Commented Sep 9, 2016 at 19:54
  • @ebakunin you are still passing the element in, aren't you? Why do you need to reference the element by it's hash when you already have it? Commented Sep 9, 2016 at 19:55

1 Answer 1

1

In your script jQuery(bookmarkHash); jquery is only returning a selector. So you can swap that out easily.

/**
 * @param {Element} el
 */
function exampleFunction(el) {
    let bookmarkHash = el.hash,
        $bookmarkElement = document.querySelector(bookmarkHash);

  /* you will need to figure out the elements offset bit */
    console.info($bookmarkElement);
}
<a id="foo" href="#bookmark" onclick="exampleFunction(this)">Some text</a>
<div id="bookmark">Hello</div>

Sign up to request clarification or add additional context in comments.

2 Comments

document.querySelector(bookmarkHash) is what I was looking for. I did not explain my problem well. Thanks for getting me the answer anyway!
Glad I could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.