skip to Main Content

To apply the DRY principle, I have a lot of document.querySelector in my code and I have created a function as such.

const documentQuerySelector = (tag, method, message) => {
  document.querySelector(`.${tag}`)`.${method}`= message;
};

Now when I call the function as such:

documentQuerySelector('message', '.textContent', '⛔️ No Number!');

the text content of the HTML text with class "message" does not get changed to "⛔️ No Number!"

the problem is with the method. When i pass in ".textContent" into the function, and use it in the document query selector as such, document.querySelector(.${tag}).${method}= message, it does not recognize the .${method}. The reason i know that this is the issue is because when i use the same function and put in ".textContent" instead, it works fine. How do i pass in that property as a variable and how do i use it in the document.querySelector?

Thanks

I tried passing it as a Template Literal and it did not work.

2

Answers


  1. You want too much DRY here at the expense of flexibility and understandability. Also the function name doesn’t infer there’s some action on the found element. The action itself is a property setter. What about a method? If you see closer you’ll notice you don’t save much typing here either. Also other programmers should learn how to handle your function. So my verdict – use document.querySelector() as it is, it’s much cleaner and imperative.

      document.querySelector('.message').textContent = '⛔️ No Number!';
    

    If you want to save your typing – use jQuery, I think it’s still valid in 2023, and almost everybody will understand your code easily:

      $('.message').text('⛔️ No Number!');
    

    If you call querySelector for the same element several times you can actually do some DRY here and save the element in a variable:

      const elMessage = document.querySelector('.message');
    
      elMessage.textContent = '⛔️ No Number!';
      // some other code
      elMessage.classList.toggle('visible', isMessageVisible);
    
    Login or Signup to reply.
  2. Not sure how it is dryer since you are basically repeating the same thing, just in a different format, but you need to use bracket notation to use a dynamic property. So you code would look something like:

    const documentQuerySelector = (selector, property, value) => {
      document.querySelector(selector)[property] = value;
    };
    
    
    documentQuerySelector('.message', 'textContent', '⛔️ No Number!');
    <div class="message"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search