I want the javascript code to highlight the background colour for all 'a' and 'i' letters in the following two paragraph tags.
I also want the image tag to show correctly. I wasn't linking to an image file in this test so showing correctly just means showing the default image.
At one point i had this code working as expected but then when i tried it later it was no longer working. The only conclusion is i must have changed something but i don't know what.
Can anyone tell me why it doesn't work?
document.querySelectorAll('p').forEach(function(myFirstItem, index) { container = '' zeroORone = 0 myFirstItem.innerHTML.split('').forEach(function(mySecondItem) { if (mySecondItem == 'a' & zeroORone == 0) { container += '<span class="yellow">' + mySecondItem + '</span>' } else if (mySecondItem == 'i' & zeroORone == 0) { container += '<span class="orange">' + mySecondItem + '</span>' } else if (mySecondItem == '<') { zeroORone = 1 container += mySecondItem } else if (mySecondItem == '>') { zeroORone = 0 container += mySecondItem } else { container += mySecondItem } }) myFirstItem.innerHTML = container })
<p>piece of a puzzle</p> <p>Planet <img src="someImage.png"> Earth</p>
I've made some changes to the HTML: I've wrapped the text in span elements. In the javascript I'm searching for the a
and the i
and I'm wrapping them in a <i>
element. Please take a look:
let spans = document.querySelectorAll('span') spans.forEach(s=>{ let text = s.innerHTML; text = text.replace(/([ai])/g, (found)=> { return `<i class='${found}'>${found}</i>` }); s.innerHTML = text; })
ia{background:yellow} ii{background:orange}
<p><span>piece of a puzzle</span></p> <p><span>Planet</span> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/pin.png"> <span>Earth</span></p>
Your code does work, except you have not added css
for classes yellow
and orange
.
document.querySelectorAll('p').forEach(function(myFirstItem, index) { container = '' zeroORone = 0 myFirstItem.innerHTML.split('').forEach(function(mySecondItem) { if (mySecondItem == 'a' && zeroORone == 0) { container += '<span class="yellow">' + mySecondItem + '</span>' } else if (mySecondItem == 'i' && zeroORone == 0) { container += '<span class="orange">' + mySecondItem + '</span>' } else if (mySecondItem == '<') { zeroORone = 1 container += mySecondItem } else if (mySecondItem == '>') { zeroORone = 0 container += mySecondItem } else { container += mySecondItem } }); myFirstItem.innerHTML = container });
.yellow { background: yellow; } .orange { background: orange; }
<p>piece of a puzzle</p> <p>Planet <img src="someImage.png"> Earth</p>
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.