jquery – Check nodeType for Pictures/Alt Attribute-ThrowExceptions

Exception or error:

I got a recursive function which goes through all HTML Child Nodes.

Is there an easy way to check if the current element is an image with element.nodeType? So I could use DOM onto this element.

Here an example of the code:

`

replaceText(document.body)

function replaceText(element){
    if(element.hasChildNodes()){
        element.childNodes.forEach(replaceText)
    } else if(element.nodeType === Text.TEXT_NODE){
//Do Something
}

`

Just like that but also for pictures and especially for the pictures alt attribute.

How to solve:

Simply use the nodeName property of the element to check if it’s an image (“IMG”) once you are sure it’s not a text node.

replaceText(document.body)

function replaceText(element){
    if(element.hasChildNodes()){
        element.childNodes.forEach(replaceText)
    } else if(element.nodeType === Node.TEXT_NODE){
      console.log("Text Found! textContent: ",element.textContent)
    }
    else if(element.nodeName = "IMG"){
      console.log("Image Found! Alt: ",element.alt)
    }
}
<html>
<body>
<p>this is text</p>
<div>this is an element</div>
<img src="https://placehold.it/22" alt="i am an image">
</body>
</html>

To get the alt property of an image, just use element.alt in your code.


TO remove the image if text in it matches a regex, just test each property you want tested:

function replaceText(element){
    if(element.hasChildNodes()){
        element.childNodes.forEach(replaceText)
    } else if(element.nodeType === Node.TEXT_NODE){
      //console.log("Text Found! textContent: ",element.textContent)
    }
    else if(element.nodeName = "IMG"){
      console.log("Image Found! Alt: ",element.alt)
      let re = /Wendler/gi
      if((element.alt != undefined &&element.alt.match(re)) || (element.src != undefined &&element.src.match(re)) || (element.title != undefined &&element.title.match(re))){ 
        element.remove()
      }
    }
}
<html>
<body>
<p>this is text</p>
<div>this is an element</div>
<img src="https://placehold.it/22" alt="i am an image">
<img src="https://placehold.it/25" alt="i am an image containing the word wendLer somewhere">
<img src="https://placehold.it/25?text=wendler" alt="i am an image">


<button onclick="replaceText(document.body)">Click to remove images</button>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *