Replace words with Javascript without removing the image

前端 未结 2 1187
终归单人心
终归单人心 2021-01-23 16:37

I want to replace the words ”morrhåren” with ”skägget” in this p-tag. I’m not supposed to change anything in the HTML-kod, only in my js-file. How can I manage to change these w

2条回答
  •  余生分开走
    2021-01-23 17:19

    You could do a simple innerHTML replacement (p.innerHTML = p.innerHTML.replace(/morrhåren/g, "skägget"), where p is a reference to the element), which wouldn't make the image disappear (the img element would just get removed and replaced with a new one for the same image), but I'm going to assume there's some reason you shouldn't do that (for instance: an event handler on the img element) since you've made a point of saying you need to leave the img element alone.

    If that's the case, you'll need to go through the p's child nodes and operate only on the text nodes (nodeType === 3), updating their nodeValue (the text of the text node). If the target word only appears at the top level, you only need to go through the p's child nodes; if it appears inside other elements in the p, you'll need a recursive function.

    For instance, assuming p is a reference to that element:

    for (var child = p.firstChild; child; child = child.nextSibling) {
        if (child.nodeType === 3) {
            child.nodeValue = child.nodeValue.replace(/morrhåren/g, "skägget");
        }
    }
    

    Again, if you needed to handle descendant elements, you'd need to add recursion to that.

    Example:

    setTimeout(function() {
        var p = document.querySelector("p");
        for (var child = p.firstChild; child; child = child.nextSibling) {
            if (child.nodeType === 3) {
                child.nodeValue = child.nodeValue.replace(/morrhåren/g, "skägget");
            }
        }
    }, 800);

    Är katten skrämd lägger den morrhåren bakåt, detsamma gör den vid slagsmål för att skydda morrhåren. Om katten är en nyfiken vinklar den morrhåren framåt.

提交回复
热议问题