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
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);
<p><img src=”http://blogg.wikki.se/wp-content/upploads/2009/06/catbyBaikal.jpg” align=”right”>
Är <span>katt</span>en skrämd lägger den morrhåren bakåt, detsamma gör den vid slagsmål för att skydda morrhåren. Om <span>katt</span>en är en nyfiken vinklar den morrhåren framåt.<p>
You can use the innerHTML property of your <p>
element (document.getElementById("/**enter id of your <p> element*/").innerHTML
) to fetch (by assigning it to a variable) or to set (by assigning a new string value to the property) the entire content of any HTML element.