не удается обнаружить ссылки с помощью приложения tagName. js в реакции - PullRequest
0 голосов
/ 23 апреля 2020

Я пытаюсь получить некоторые элементы, когда они являются ссылками, чтобы я мог проверить их href значения. Я пытаюсь запустить некоторый код, который проходит через все узлы и childNodes в моем приложении, тогда всякий раз, когда я нахожу тег <a>, но я не могу обнаружить их, используя мои текущие логи c.

Я оглянулся и смог получить тип элемента с помощью element.tagName, возможно, что-то не так с моей структурой l oop? Надеясь, что кто-то может помочь мне или дать мне несколько советов.

Мой JSX:

<div id="app">
        <p>thats dope</p>
        <div>
          some stuff here
          <img src = {deer} width="80px" height="80px" alt="a deer"></img>
        </div>

        <div>
          <p>here there will be a sample node to check out</p>
          <a href="https://sdfd.com">link</a>
          <TestNode/>
        </div>
      </div>

Моя функция такова:

checkNodes= (id,escapeChars,whiteListURLS) =>{
    var app = document.getElementById(id)

    if (app.hasChildNodes()) {
      let children = app.childNodes;

      //check every child in the dom within the passed in ID
      for (let i = 0; i < children.length; i++) {
          console.log(children[i])

                  for(let x = 0; x < escapeChars.length; x++ ){
                      if(children[i].nodeValue !== undefined && children[i].nodeValue === escapeChars[x] ){
                          console.log('error detected escape chars ',children[i])
                          return false     
                      }

                      //CHECK FOR <A> TAG

                      if(children[i].tagName.toLowerCase() === "a"){
                        console.log('this is a link')
                        if(children[i].getAttribute("href") !== whiteListURLS[x]){
                          console.log('error detected suspect url ',children[i])
                        }
                      }

                  }

          //check all children inside a child
          for(let j = 0; j < children[i].length; j++){
              console.log(children[i][j])

                      for(let z = 0; z < escapeChars.length; z++ ){
                          if(children[i][j].nodeValue !== undefined && children[i][j].nodeValue === escapeChars[z]){
                              console.log('error detected escape chars ',children[i][j])
                              return false 
                          }

                   //CHECK FOR <A> TAG
                          if(children[i][j].tagName.toLowerCase() === "a") {
                            console.log('this is a link')
                            if(children[i][j].getAttribute("href") !== whiteListURLS[z]){
                              console.log('error detected suspect url ',children[i][j])
                            }
                          }
                      }
                  } 
              }
          }
      }

1 Ответ

0 голосов
/ 23 апреля 2020

Я предлагаю вам использовать document.querySelectorAll, что намного проще и чище. Это поможет вам запрашивать только теги a. https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

  const checkNodes= (id,escapeChars,whiteListURLS) =>{
    const root = document.getElementById("root");
    const anchors = root.querySelectorAll('a'); // find all a tags within root node
    console.log(anchors);
    for (let i = 0; i < anchors.length; i++) {
      console.log(anchors[i].href);
    }
  }
...