简体   繁体   中英

Find and replace text within a class attribute on a webpage using a javascript bookmarklet

I'm trying to create a javascript bookmarklet that will find and replace text set as a class with a different text. For example, I want to find 'shoe' and replace it with 'socks,' see below.

div class=' shoe '

and replace it with

div class=' socks '

I found this: Bookmarklet Help: Creating a Find/Replace Bookmarklet .

javascript:function%20htmlreplace(a,b,element){if(!element)element=document.body;var%20nodes=element.childNodes;for(var%20n=0;n<nodes.length;n++){if(nodes[n].nodeType==Node.TEXT_NODE){nodes[n].textContent=nodes[n].textContent.replace(new%20RegExp(a,'gi'),b);}else{htmlreplace(a,b,nodes[n]);}}}htmlreplace(prompt("Text%20to%20replace:","old"),prompt("Replacement%20text:","new"));

But I'm not sure how to manipulate the script to cater my needs above to replace the text within the attribute.

I've no experience with javascripts whatsoever, but I'm trying to understand the language, so please forgive me if I'm messing up the terminology. Any help is appreciated, thanks!

If you have only 1 element with that class name, you could use

javascript:document.getElementByClassName("shoe").className = "socks";

but for all classes, you could use

var d=document.getElementByClassName("shoe");for(var i=0;i<d.length;i++){d[i].className="socks";}

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