단락 innerHTML에서 모든 링크의 배열을 가져 와서 textContent와 비교하여 내용과 함께 시작 및 끝 색인을 저장하고 싶습니다.
<p id ="1">This is a <a href ="/hey">Link</a> and this is also a <a href="/hey">Link</a></p>
그래서 이것을 위해 나는 다음과 같은 것을 얻으려고합니다.
//I know this is formatted weird, just showing an example of what data would like at end.
links = [
'link1': { start_index: 11, end_index: 14, href: '/hey, text: 'Link'},
'link2': { start_index: 35, end_index: 38, href: '/hey, text: 'Link'},
]
start_index 및 end_index는 textContent 단락의 링크 위치를 기반으로합니다.
indexOf ()를 사용해 보았습니다.
str = document.getElementById("1").innerHTML;
var index_start = str.indexOf("<a href ="/hey">Link</a>");
그러나 이것은 innerHTML의 링크 색인을 반환합니다. textContent에서 위치를 얻는 방법이나 모든 링크의 위치를 얻는 방법을 모르겠습니다.
혼란 스러우면 감사합니다.
여기에 시작 개념 솔루션이 있습니다.
의 복제본을 만든 <p>
다음 해당 복제본의 링크를 자리 표시 자로 대체 ||
하여 해당 자리 표시자를 사용하여 텍스트 문자열을 배열로 분할 할 수 있습니다.
그런 다음 링크를 객체 배열로 매핑하고 분할 된 텍스트 배열에서 이전 텍스트 길이를 가져옵니다 (단락의 시작 부분이 아니라 지금은 이전 링크).
조금 더 개발하면 링크를 텍스트에 다시 넣을 수 있도록 리버스 엔지니어링하는 것이 매우 쉽습니다.
const p = document.querySelector('p');
const txtArray = getTextInArray(p)
const links = Array.from(p.querySelectorAll('a')).map((el, i) => {
return {
href: el.href,
linkTxt: el.textContent,
prevTxtLength: txtArray[i].length
}
})
console.log(links)
function getTextInArray(p) {
let clone = p.cloneNode(true);
clone.querySelectorAll('a').forEach(a => a.replaceWith('||'));
return clone.textContent.split('||');
}
<p>Some text <a href="foo">Foo</a> some more text <a href="boo">Boo</a></p>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다