your programing

JavaScript에서 "원시"href 콘텐츠를 얻는 방법

lovepro 2020. 12. 30. 19:51
반응형

JavaScript에서 "원시"href 콘텐츠를 얻는 방법


상대 링크 인 모든 링크를 찾으려는 GreaseMonkey 스크립트를 작성하려고합니다. 그렇게하는 방법은 href의 내용을 /^https?:///.

하지만 앵커의 href 속성에 액세스 할 때 항상 정규화되거나 "http"를 포함하는 형식으로 요리된다는 것을 알았습니다. 즉, HTML에 다음이 포함 된 경우 :

<a id="rel" href="/relative/link">inner</a>

액세스

document.getElementById("rel").href

보고

http://example.com/relative/link

href 속성의 원시 데이터에 어떻게 액세스 할 수 있습니까?

또는 상대 링크를 찾는 더 좋은 방법이 있습니까?


대신 getAttribute방법을 시도하십시오 .


전형적인. 나는 질문을 게시 한 직후에 스스로 알아 냈다.

대신에:

anchor.href

사용하다:

anchor.getAttribute("href")

물론 다른 사람들이 대답하는 것보다이 대답을 입력하는 데 시간이 더 걸렸습니다. (젠장, 너희들은 빠르다.)


다음은 테스트를 위해 실행할 수있는 코드 스 니펫입니다.

const anchors = document.getElementsByTagName('a');

for (let anchor of anchors) {
  let hrefFullPath = anchor.href;
  let hrefRelativePath = anchor.attributes.href.value;

  console.log('hrefFullPath', hrefFullPath);
  console.log('hrefRelativePath', hrefRelativePath);
}

http://localhost:4200에 있으며 질문에 표시된대로이 문서가 있다고 가정 해 보겠습니다 .

<a id="rel" href="/relative/link">inner</a>

이 앵커의 속성 값 href은 다음과 같습니다.

document.getElementById('rel').attributes.href.value => /relative/link

앵커의 href값은 다음과 같습니다.

document.getElementById('rel').href =>  http://localhost:4200/relative/link

도움이되기를 바랍니다.

참조 URL : https://stackoverflow.com/questions/1550901/how-to-get-raw-href-contents-in-javascript

반응형