Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第505天 写一个js方法,输入指定类型的选择器(id,class,tagName)可以返回匹配的DOM节,要求兼容和性能 #2854

Open
haizhilin2013 opened this issue Sep 1, 2020 · 2 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第505天 写一个js方法,输入指定类型的选择器(id,class,tagName)可以返回匹配的DOM节,要求兼容和性能

3+1官网

我也要出题

@haizhilin2013 haizhilin2013 added the js JavaScript label Sep 1, 2020
@censek
Copy link

censek commented Oct 19, 2020

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <div id="first">
    <label>请输入选择器的类型(id/class/tagName):</label><input type="text" id="type">
  </div>
  <div class="second">
    <label>请输入想要查找的具体的id/class/tagName:</label><input type="text" id="input">
  </div>
  <button onclick="dom()">查询</button>
</body>
<script>
  function dom() {
    let output;
    let type = document.getElementById("type").value;
    let input = document.getElementById("input").value;

    if (type === "id") {
      output = document.getElementById(input);
      console.log(output);
    } else if (type === "class") {
      output = document.getElementsByClassName(input);
      console.log(output);
    } else if (type === "tagname") {
      output = document.getElementsByTagName(input);
      console.log(output);
    } else {
      console.log("error:输入的内容有误,请检查!")
    }
  }
</script>

</html>

@wind8866
Copy link

wind8866 commented Mar 1, 2022

在本页面打开控制台即可运行

const selectElementAll = (selecter) => {
  selecter = selecter.trim()
  if (/^\#[a-zA-Z_\-]+$/.test(selecter)) {
    return document.getElementById(selecter.replace('#', ''))
  } else if (/^\.[a-zA-Z_\-]+$/.test(selecter)) {
    return document.getElementsByClassName(selecter.replace('.', ''))
  } else if (/^[a-zA-Z]+$/.test(selecter)) {
    return document.getElementsByTagName(selecter)
  } else {
    throw new Error(`无法解析 ${selecter}`)
  }
}
selectElementAll('#start-of-content')
selectElementAll('.show-on-focus')
selectElementAll('DiV')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

3 participants