最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to jump to HTML element by class instead of id? - Stack Overflow

programmeradmin3浏览0评论

I know that you can jump to elements by id but is it possible to jump to elements by class?

Am I going to have to use javascript to add an id to the element with that class name?

It would be a pain to add ids manually every time, the class names will already be there.

*I could have worded my question a bit better. I meant to use class names that are already there as anchor tags to jump to. The html I'm working with has class names for a LOT of individual elements and no ids. I'm wanting to jump to those elements without having to add an id to each and every one.

I know that you can jump to elements by id but is it possible to jump to elements by class?

Am I going to have to use javascript to add an id to the element with that class name?

It would be a pain to add ids manually every time, the class names will already be there.

*I could have worded my question a bit better. I meant to use class names that are already there as anchor tags to jump to. The html I'm working with has class names for a LOT of individual elements and no ids. I'm wanting to jump to those elements without having to add an id to each and every one.

Share Improve this question edited Jul 30, 2013 at 4:51 Unwieldy Lunchbox asked Jul 30, 2013 at 4:30 Unwieldy LunchboxUnwieldy Lunchbox 1031 gold badge1 silver badge5 bronze badges 3
  • developer.mozilla/en-US/docs/Web/API/… – go-oleg Commented Jul 30, 2013 at 4:31
  • Did you check out my answer? – Derek 朕會功夫 Commented Jul 30, 2013 at 4:51
  • 1 I would like to have a solution which allow me to use it in a url like actually it is possible with an id. In other words, a no javascript solution. – alex Commented Jul 27, 2017 at 20:01
Add a ment  | 

4 Answers 4

Reset to default 5
window.scrollTo(0, document.querySelector(".className").offsetTop);

http://jsfiddle/DerekL/kEFp7/

FYI: On chrome you can create an anchor to a text, which will take you to that section and also highlight the text.

The most mon syntax is: #:~:text=Some text

And all possible usages are: #:~:text=[prefix-,]textStart[,textEnd][,-suffix] which would allow you to select text from , to , inclusive / exclusive

Consider the following example links:

  • Selecting text "Private Address Space"

  • Selecting text from the word "advantage" up to word "space"

  • Selecting text from the word "advantage" up to word "space" which has a word "by" after

  • Selecting the paragraph between header titles "Introduction" and "2. Motivation"

Specs: W3C munity draft report

Even though i wouldn't remend to use a class to jump to an element...

You can use this a couple of different jQuery such as ScrollTo or ScrollTop

document.getElementsByClassName('className')

or, using jQuery

$('.className')
发布评论

评论列表(0)

  1. 暂无评论