I have a generated string like this
tesgddedd<br> <div><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div>
I want to get the div containing the img and add a css class in this div to get a new string like this
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.
What should I do?
P粉7181655402023-09-09 10:02:25
It is recommended to use an HTML parser instead of regular expressions and use .querySelector
to get the div
with img
.
Use native browser interfaces DOMParser and .parseFromString to parse HTML.
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"); // 获取包含直接子img的div元素 // 注意:它也返回其他子元素 const divWithImg = doc.querySelector("div:has(> img)"); if (divWithImg) { // 捕获到带有img的div console.log("Before", divWithImg); // 添加类名 divWithImg.className = "myCssClass" // 更新带有类名的div console.log("After", divWithImg); } else { console.log("No match found."); }
The code snippet below is a visual example
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"); // 获取包含直接子img的div元素 // 注意:它也返回其他子元素 const divWithImg = doc.querySelector("div:has(> img)"); if (divWithImg) { // 用于在页面上预览 const code = document.querySelector("code"); // 捕获到带有img的div code.textContent = ` Before: ${divWithImg.outerHTML} `; console.log("Before", divWithImg); // 添加类名 divWithImg.className = "myCssClass" // 更新带有类名的div code.textContent += ` After: ${divWithImg.outerHTML} `; console.log("After", divWithImg); } else { console.log("No match found."); }
<pre><code></code></pre>