user2144857
user2144857

Reputation:

How do i check if a node exists with jQuery?

I want to check for a particular node exists and perform a particular set of instructions. I have two text elements in an xml file, for instance, part of the XML file is:

<text transform="matrix(1 0 0 1 818.252 302.8809)">
  <tspan x="0" y="0" font-family="'Arial-BoldMT'" font-size="14.7311">INLET</tspan>
  <tspan x="-4.867" y="15.401" font-family="'Arial-BoldMT'" font-size="14.7311">FILTER</tspan>
</text>

<text transform="matrix(1 0 0 1 792.9395 64.6396)" font-family="'Arial-BoldMT'"font-size="14.7311">
  COMPENSATOR
</text>

Notice one node has a tspan wrapped inside and the other doesn't. I want to do an if statement that checks for the tspan node and return the text inside and also return the text inside of the text node. What would the if statement look like?

Upvotes: 1

Views: 1745

Answers (1)

m59
m59

Reputation: 43755

There are notes for all of the code, so it should be easy to understand!

Live demo (click).

//find all "text" nodes
var $texts = $('text');

//loop through each "text" node
$texts.each(function(i, elem) {
  //make a jQuery object from the node
  var $text = $(elem);
  //look for "tspan" children
  var $tspans = $text.children('tspan');
  //if there are any children
  if (!$tspans.length) {
    //get the "text" node's text
    var text = $text.text();
    console.log('No tspan: '+text);
  }
  else { //if there are children tspans
    //loop through each tspan
    $tspans.each(function(i, tspan) {
      //make a jQuery object from the tspan
      var $tspan = $(tspan);
      //get the tspan's text
      var text = $tspan.text();
      console.log('From tspan: '+text);
    });
  }
});

Upvotes: 1

Related Questions