Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is jQuery for Document.createElementNS()?

What is jQuery for Document.createElementNS()?

function emleGraphicToSvg(aGraphicNode) {
  var lu = function luf(aPrefix){
    switch (aPrefix){
      case 'xhtml': return 'http://www.w3.org/1999/xhtml';
      case 'math':  return 'http://www.w3.org/1998/Math/MathML';
      case 'svg':   return 'http://www.w3.org/2000/svg';
      }
    return '';
    };
  var svg = document.evaluate("svg:svg",
    aGraphicNode, lu, XPathResult.FIRST_ORDERED_NODE_TYPE, null).
    singleNodeValue;
  $(svg).children().remove();
  rect = document.createElementNS(lu('svg'), "rect");
  rect.setAttribute("x", "35");
  rect.setAttribute("y", "25");
  rect.setAttribute("width", "200");
  rect.setAttribute("height", "50");
  rect.setAttribute("class", "emleGraphicOutline");
  svg.appendChild(rect);
  }

The code is a simplified fragment from Emle - Electronic Mathematics Laboratory Equipment JavaScript file emle_lab.js.

The Look-Up-Function, luf(), maps a complete reference to a shorten name for the namespace in the XPath string and createElementNS(). The existing svg:svg is located, removed and replaced by a new rectangle.

like image 281
CW Holeman II Avatar asked Apr 03 '10 18:04

CW Holeman II


People also ask

What is createElementNS?

createElementNS() Creates an element with the specified namespace URI and qualified name. To create an element without specifying a namespace URI, use the createElement() method.

What is this function in jQuery?

The this Keyword is a reference to DOM elements of invocation. We can call all DOM methods on it. $() is a jQuery constructor and in $(this), we are just passing this as a parameter so that we can use the jQuery function and methods.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


2 Answers

What is jQuery for Document.createElementNS()?

That would be:

$(document.createElementNS('namespace', 'tag'))

So in the OP's case:

rect = $(document.createElementNS(lu('svg'), 'rect'))
    .addClass('emleGraphicOutline')
    .attr({
        x: 35,
        y: 25,
        width: 200,
        height: 50
    });

But not much is really gained by using jQuery for that, of course. In any case, one can always wrap DOM nodes in jQuery with e.g. $(rect) after creating rect with vanilla JS.

Note that jQuery has other issues with SVG, such as breaking viewBox due to lowercasing attributes, so plain JS must still be used for some attributes.

like image 146
Jason C Avatar answered Sep 23 '22 16:09

Jason C


For SVG, I have used Keith Wood's jquery.svg for some evaluation type projects.

like image 38
ndim Avatar answered Sep 27 '22 16:09

ndim