简体   繁体   中英

Remove custom attribute from all <a> element in dynamic HTML container

How to remove index attribute from all elements in the variable container.innerHTML. Html is generated dynamically.

var container.innerHTML = test &nbsp;&nbsp; <a class ="test-image-class" index="0" href="" ><span>testimage</span></a> &nbsp;&nbsp;
     &nbsp;&nbsp; <a class = "test-image-class" index="1" href="" ><span>testimage</span></a> &nbsp;&nbsp;
    these two images are not matching &nbsp;&nbsp; <a class = "test-image-class" index="3" href="" ><span>testimage</span></a> &nbsp;&nbsp;

An easy solution can be just replace with regular expression

`test &nbsp;&nbsp; <a class ="test-image-class" index="0" href="" ><span>testimage</span></a> &nbsp;&nbsp;
     &nbsp;&nbsp; <a class = "test-image-class" index="1" href="" ><span>testimage</span></a> &nbsp;&nbsp;
    these two images are not matching &nbsp;&nbsp; <a class = "test-image-class" index="3" href="" ><span>testimage</span></a> &nbsp;&nbsp`.replace(/index="[\d]+"/g, '')

Here replace is the string replace function for JavaScript it's generally accepts two parameter one search string or regex pattern & replace string. Here /index="[\d]+"/g is the pattern '' is the replace string. g is used to match all.

A Regex is the easiest way out of this. The search below uses index

let str = `test &nbsp;&nbsp; <a class ="test-image-class" index="0" href="" ><span>testimage</span></a> &nbsp;&nbsp;
&nbsp;&nbsp; <a class = "test-image-class" index="1" href="" ><span>testimage</span></a> &nbsp;&nbsp;
these two images are not matching &nbsp;&nbsp; <a class = "test-image-class" index="3" href="" ><span>testimage</span></a> &nbsp;&nbsp`;

let re = /index="[^"]*"/gi;
let result = str.replace(re, "");
console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM