Search code examples
javascriptqueryselector

Search by selector by class name and style property JS


I am trying to return the desired element by its unique properties. To do this, I need to use something like this code. I have a mistake in it, how do I make this entry correct?

document.querySelector('div[class="className" style*="text-decoration:line-through"]')

Solution

  • You need to separate the attribute selectors:

    document.querySelector('div[class="className"][style*="text-decoration:line-through"]');
    

    Also note that as you're using a class to target the elements, use a class selector for better performance:

    document.querySelector('div.className[style*="text-decoration:line-through"]');
    

    Lastly, your style selector is incredibly brittle, and very easily broken. For example, if someone validly uses text-decoration: line-through then it will not be matched. I would strongly suggest you use a class to apply the style and select the element.