skip to Main Content

i have a generated string like it

tesgddedd<br> <div><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div>

I want to get div contains img and to add css class in this div et to have a new string liket it

tesgddedd<br> <div class="myCssClass"><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div>

I tried this method

let myString = 'tesgddedd<br> <div><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div>'
console.log('My new String with div class  : ',myString.match(/<div [^>]*img="[^"]*"[^>]*>/gm)[0])

It doesn’t work.

How can I do it please ?

2

Answers


  1. Recommend using an HTML parser instead of regex and using .querySelector to grab the div with img.

    const generatedHTML = "tesgddedd<br> <div><img style='max-width: 35rem;' src='folder/mypicture.jpg'><div> <br></div></div>";
    
    const parser = new DOMParser();
    const doc = parser.parseFromString(generatedHTML, "text/html");
    
    // Retrieve element that is a div that contains a direct img as child
    // Note: it also returns other children as well
    const divWithImg = doc.querySelector("div:has(> img)");
    
    if (divWithImg) {
      // Captured div with img
      console.log("Before", divWithImg);
      
      // Add class
      divWithImg.className = "myCssClass"
      
      // Updated div with class name
      console.log("After", divWithImg);
    } else {
      console.log("No match found.");
    }
    

    See below snippet to visually see it work.

    const generatedHTML = "tesgddedd<br> <div><img style='max-width: 35rem;' src='folder/mypicture.jpg'><div> <br></div></div>";
    
    const parser = new DOMParser();
    const doc = parser.parseFromString(generatedHTML, "text/html");
    
    // Retrieve element that is a div that contains a direct img as child
    // Note: it also returns other children as well
    const divWithImg = doc.querySelector("div:has(> img)");
    
    if (divWithImg) {
      // Used to just preview on page
      const code = document.querySelector("code");
      
      // Captured div with img
      code.textContent = `
        Before:
        ${divWithImg.outerHTML}
       `;
      console.log("Before", divWithImg);
      
      // Add class
      divWithImg.className = "myCssClass"
      
      // Updated div with class name
      code.textContent += `
        After:
        ${divWithImg.outerHTML}
       `;
      console.log("After", divWithImg);
    } else {
      console.log("No match found.");
    }
    <pre><code></code></pre>
    Login or Signup to reply.
  2. To add a CSS class to the containing the , you can use regular expressions in JavaScript. Here’s an example of how you can achieve it:

    let myString = 'tesgddedd<br> <div><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div>';
    
    // Regular expression pattern to match the <div> containing the <img>
    let pattern = /<div([^>]*)><img([^>]*)><div>/gm;
    
    // Replace the matched <div> with the updated <div> including the CSS class
    let updatedString = myString.replace(pattern, '<div class="myCssClass"$1><img$2><div>');
    
    console.log('My new String with div class:', updatedString);
    
    In this code, we're using the replace() function with a regular expression pattern to match the <div> element containing the <img>. We capture the attributes of the <div> using parentheses and then replace it with the updated <div> that includes the desired CSS class.
    
    The resulting updatedString will have the desired format:
    tesgddedd<br> <div class="myCssClass"><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div>

    Please note that manipulating HTML strings with regular expressions can be error-prone, especially for complex HTML structures. It’s generally recommended to use a proper HTML parser or DOM manipulation library for more reliable and maintainable results.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search