I am trying to find the correct a-tag within a DOM. For this I need to parse its direct neighbors:
let strongTags = document.querySelectorAll('div.entry p strong');
for (let i = 0; i < strongTags.length; i++) {
if (strongTags[i].textContent.toLowerCase().match("size")) {
let dbATag;
if (strongTags[i].nextElementSibling) {
if (strongTags[i].nextElementSibling.tagName == "A") {
dbATag = strongTags[i].nextElementSibling;
} else if (strongTags[i].nextElementSibling.nextElementSibling) {
if (strongTags[i].nextElementSibling.nextElementSibling.tagName == "A") {
dbATag = strongTags[i].nextElementSibling.nextElementSibling;
}
}
}
}
}
As you can see, I don't know if the a tag is in nextElementSibling or in the second nextElementSibling. Theoretically there could be a third one, but I never saw it in the data. I'd like something like a querySelector('a') directly from the strongTags[i] position within the current parent. But that's another one of my don't knows.
My current main problem is that I can't test if strongTags[i].nextElementSibling exists and if tagName is A, like this:
if (strongTags[i].nextElementSibling && strongTags[i].nextElementSibling.tagName == "A").
Even though it doesn't exist, the interpreter still tries to test for tagName as well. This results in an error that stops further execution of my script. That's why I split it into two lines for now.
How can I solve this a bit more beautiful? :)
Aucun commentaire:
Enregistrer un commentaire