Using JavaScript and regular expressions to extract div tags containing img tags
P粉252116587
P粉252116587 2023-09-08 15:31:48
0
1
578

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粉252116587
P粉252116587

reply all(1)
P粉718165540

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

"; 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

"; 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."); }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!