简体   繁体   中英

Bookmarklet to replace input values of random name input fields

I would like to create a bookmarklet that replaces all values of every input field on a webpage. There are a lot ot them but they can be split into two categories by their name .

Example:

<input class="Class1" name="ABC_randomnumbers" value="randomnumber" type="text">
<input class="Class1" name="DEF_randomnumbers" value="randomnumber" type="text">

Input fields with its names starting with ABC would receive the value X, input fields with its names starting with DEF would receive the value Y. I tried

javascript:document.body.innerHTML=document.body.innerHTML.replace(/input class="Class1" name="ABC_(\d+)" value="\d+"/g,'input class="Class1" name="ABC_$1" value="X"'); document.body.innerHTML=document.body.innerHTML.replace(/input class="Class1 name="DEF_(\d+)" value="\d+"/g,'input class="Class1" name="DEF_$1" value="Y"');

to replace all occurences of these strings in the HTML but it messes up the whole page, for example it deletes the contents of the tag. I read something about getElementsByName , but they don't have the same name and I can't get regexp work with getElementsByName .

I would refrain from editing the base HTML in such a way. A better option is to edit the page with Javascript code. I provided an example below:

var allInputs = document.getElementsByTagName("input");

for (var i = 0; i < allInputs.length; i++) {
    if(allInputs[i].name.startsWith("ABC_")) {
        //Do Logic here
    }

    //Other cases here
}

Shorthand version provided below:

Array.from(document.getElementsByTagName("input")).forEach(function(input) {
    if(input.name.startsWith("ABC_")) {
        //Do Logic here
    }

    //Other cases here
});

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