0

Just getting started with document.querySelector in JavaScript. Why would let result = document.querySelector('Lh') return a null. I have tried many permutations with a div as part of the search string but there must be something different about it in a div? Wildcard suggestions...

let result1 = document.querySelector('[class^="Lh(21px)"]')
let result2 = document.querySelector('[class^=".Lh(21px)"]')
let result3 = document.querySelector('[class^="Lh"]')
let result4 = document.querySelector('[class^=".Lh"]')

All return nulls.

<div class="" data-test="quote-mdl" data-yaft-module="tdv2-applet-summary">
    <div class="Mb(25px) smartphone_Px(20px)">
        <h3 class="Mb(5px)"><span>Summary</span></h3>
        <div class="Lh(21px)">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
            Sed et magna magna. Praesent in condimentum quam. Phasellus dui ligula,
            tincidunt porta fermentum nec. rhoncus id enim. Duis tempor, tellus at
            fermentum consectetur, nisl ipsum placerat metus, sed aliquam turpis enim eget erat.
        </div>
    </div>
</div>
SuperDave
  • 373
  • 5
  • 14
  • I’m not sure the class names you’ve used in your HTML here are syntactically valid - [further SO reading](https://stackoverflow.com/questions/448981/which-characters-are-valid-in-css-class-names-selectors) – esqew Jan 24 '21 at 20:17
  • The HTML is in a website I don't control. – SuperDave Jan 24 '21 at 23:12

2 Answers2

2

<div class="Lh(21px)">Lorem ipsum dolor ...

The name of your class is Lh(21px) and not Lh, if you want to match any class name that begins with Lh, use the solution provided in this answer:

let result1 = document.querySelector('[class^="Lh"]');
console.log(result1)
<div class="" data-test="quote-mdl" data-yaft-module="tdv2-applet-summary">
    <div class="Mb(25px) smartphone_Px(20px)">
        <h3 class="Mb(5px)"><span>Summary</span></h3>
        <div class="Lh(21px)">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
            Sed et magna magna. Praesent in condimentum quam. Phasellus dui ligula,
            tincidunt porta fermentum nec. rhoncus id enim. Duis tempor, tellus at
            fermentum consectetur, nisl ipsum placerat metus, sed aliquam turpis enim eget erat.
        </div>
    </div>
</div>
TheEagle
  • 5,808
  • 3
  • 11
  • 39
0

According to MDN:

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

Lh is not a valid selector, because is not a tag but a classname. So you should change your code to this:


const divElement = document.querySelector(".Lh\\(21px\\)")

[EDIT]: Add the backslash if you are using the parenthesis

Roberto
  • 253
  • 1
  • 9