1

Let me keep is simple. Scrollit.js, you set a data-scroll attribute on the navigation link, and a data-index where the content you want it to scroll to.

You don't need to set a specific ID on either thing for it to work. So why when I am reading about using data- attributes, the JS always starts with getelementbyID(#..)?

I'm looking to put together a micro-framework that uses this.

2
  • 1
    getElementById is accessing DOM element via id attribute. for data attribute, use that elements dataset attribute. developer.mozilla.org/en/docs/Web/API/HTMLElement/dataset Commented Apr 28, 2017 at 5:42
  • 1
    Appreciated @marmeladze I was reading on the same site, but everything I saw before that kept referencing to use getElementbyID, and then the daa-attribute Commented Apr 28, 2017 at 6:00

1 Answer 1

1

There are several ways accessing DOM elements.

$x() will let you catch nodes with given xPath expression.

querySelector will also let you achieve the same result (Type help() in firefox console, it will take you to web helpers page).

I like querySelectors, so I'll use them.

var changes_indexes_to_cubes = function() {
  var indexed = document.querySelectorAll("[data-index]");
  for(var i=0; i<indexed.length; i++) {
    indexed[i].innerHTML = parseInt(i)**3;
  }
}


document.querySelector("[data-foo]").addEventListener('click', changes_indexes_to_cubes)
<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
  <div>
    <span class="lorem" data-index="1">0</span>
    <span class="lorem" data-index="2">1</span>
    <span class="lorem" data-index="3">2</span>
    <span class="lorem" data-index="4">3</span>
    <span class="lorem" data-index="5">4</span>
    <span class="lorem" data-index="6">5</span>
    <span class="lorem" data-index="7">6</span>
    <span class="lorem" data-index="8">7</span>
    <span class="lorem" data-index="9">8</span>    
    <span class="lorem" data-index="10">9</span>
    <p class="Lorem" data-foo="foo">Click me to change everything</p>  
  </div>
</body>
</html>

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

Comments

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.