How to use css selector on SVGjs - javascript

I try multiple javascript libraries to work with svg
now i play with svgjs.dev
but i don't know how to use css selector like snapsvg
var result1 = Snap.select('#id_select');
var result2 = Snap.select('.class_selector');
what is the solution for svgjs ?
i can select childrens but i need make a loop to compare properties for every child :(
what is the shortcut fot get some element inner svg document?
thanks for your attention

You would use the get() method as per doc for id, or use jquery if needing a class
var element = SVG.get('my_element')
element.fill('#f06')

From SVG.js v2 it is possible to use selectors. It's what you would expect it to be:
var elements = SVG.select('rect.my-class').fill('#f06')
You can also search within a parent element:
var elements = group.select('rect.my-class').fill('#f06')
But as #Ian suggested, jQuery or Zepto are options as well. This is all described in the docs:
https://svgdotjs.github.io/referencing/#using-css-selectors

Related

Create new element from selector?

How can I create a new element using just a selector? (e.g. .myclass, #myid or a:not(.someclass)) Basically there is no way for you to tell if the element is a div, span, li, an anchor, if it's a div with a class or with an id and so on.
In jQuery I know you can do $(selector) to get a usable DOM object. But how can this be done in JavaScript?
In jQuery I know you can do $(selector) to get a usable DOM object...
Not to create one. jQuery will do a search in the DOM for existing matches. You can do $("<div>") and such (note that's HTML, not a CSS selector) to create elements, but jQuery doesn't have a feature for creating elements from CSS selectors.
But how can this be done in JavaScript?
You'll have to parse the selector, and then use document.createElement with the tag name, and then set any classes or other things the selector describes on the new element.
CSS selectors aren't very hard to parse. You'll be able to find a lib that does it. (jQuery has Sizzle, which is a selector engine, built in and Sizzle is open source. It will naturally have code to parse selectors.)
Mootools does this.
new Element('#name.class')
yields
<div id=​"name" class=​"class">​</div>​
The answer appears to be that there is no built-in way of doing this. Maybe there’s a library which does the job.
However, it’s not to hard to write a function to create an element from a simple selector:
/* createElementFromSelector(selector)
================================================
Usage: element#id.class#attribute=value
================================================ */
function createElementFromSelector(selector) {
var pattern = /^(.*?)(?:#(.*?))?(?:\.(.*?))?(?:#(.*?)(?:=(.*?))?)?$/;
var matches = selector.match(pattern);
var element = document.createElement(matches[1]||'div');
if(matches[2]) element.id = matches[2];
if(matches[3]) element.className = matches[3];
if(matches[4]) element.setAttribute(matches[4],matches[5]||'');
return element;
}
var testitems = [
'div#id.class#attribute=value',
'div#id.class#attribute',
'div',
'div#id',
'div.class',
'#id',
'.class',
'#id.class',
'#whatever'
];
testitems.forEach(item => {
var element = createElementFromSelector(item);
console.log(element);
});
The tricky part is the regular expression. You can see it in detail here: https://regex101.com/r/ASREb0/1 .
The function only accepts selectors in the form element#id.class#attribute=value with the any of components being optional, as you see in the test items. I think including pseudo classes is probably pushing the friendship, but you might like to modify it to include multiple real classes.

displaying specific text on tumblr [duplicate]

It looks like JQuery does the search in the current document when using a selector.
How to search for an element only inside a div element?
jQuery selectors work very much like CSS selectors, which you may be more familiar with.
First, select the div, and then descend from that:
$('#my-div').find('some-selector').
or build your selector to match children of the element in question:
$('#my-div some-selector')
Old question, but everyone seems to have missed the scoped jQuery selector (using the scope you desired, i.e. your div selector, as the second parameter)
e.g. use
var $matches = $('.adiv', '#mydiv');
This is a shorter equivalent of:
var $matches = $('#mydiv').find('.adiv');
var elems = jQuery(".foo", jQuery("#divYourWantToLimitTo") ); //BAD
//or
var elems = jQuery("#divYourWantToLimitTo .foo"); //Better
//or
var elems = jQuery("#divYourWantToLimitTo").find(".foo"); //BEST
jQuery provides several ways to search for specific elements:
$("#your_div").find(".your_things"); //Find everything inside
//-or-
$("#your_div").filter(".your_things"); //Find only the top level
//-or-
$("#your_div .your_things"); //Easiest
var elements = $('div ' + yourSearch);
$('div-selector').find('the selector-you-are-looking-for');

How would I select a part of a class and replace it with jQuery?

I'm trying to select the class p100 and replace it with a number that will be inputted by the user, does anyone know how to keep the "p" and replace the number in the class using jQuery?
<div class="c100 p100 small green storyline">
something like this can be done: $('.p100').removeClass('p100').addClass('p'+uservalue);
edit:
if you have more that one div with class p100:
$('.p100').each(function(){
$(this).removeClass('p100').addClass('p'+uservalue);
})
var item = $('.p100');
$('#button').click(() => {
item.removeClass('p100');
item.addClass('p200')
})
Working JSFiddle with visuals
You can set the class by using .attr(), like this:
$("#td_id").attr('class', 'newClass');
If you want to add a class, use .addclass() instead, like this:
$("#td_id").addClass('newClass');
Or a short way to swap classes using .toggleClass():
$("#td_id").toggleClass('change_me newClass');
Read more about Class attributes
While the other answers mention good ways with jquery, I'd like to add a vanilla javascript solution :) :
for(let elem of document.getElementsByClassName('p100'){
elem.classList.remove('p100');
elem.classList.add('p'+uservalue);
}
If you want to restrict it to divs (the above code will match every element with class p100) just replace document.getElementsByClassName('p100') with document.querySelectorAll('div .p100') :).
We could replace the two calls of .remove and .add with one call of .replace like this : elem.classList.replace('p100','p'+uservalue), Currently this function isn't implemented in all browsers.
Pay attention that classList is supported in IE10+, if you need IE9 support you need a polyfill, MDN already gives one and the polyfill provides replace function above too, see here : https://developer.mozilla.org/en-US/docs/Web/API/Element/classList (scroll down to see the polyfill)
for document.querySelectorAll support, it's supported in IE8(CSS2 selectors only) and IE9+(all CSS selectors including CSS3 ones).
Using String.match & RegExp.test
var pattern = new RegExp("/p[0-9]*/");
var className = $('div').attr('class')
if (pattern.test(className)) {
var class = className.match(pattern)[0];
$('div').removeClass(class).addClass('p' + integer);
}

Select the child[ren] of an element as one would select the descendant[s]

Say I have an HTMLElement:
var hoop = otherLibrary.getHoop()
I can select its descentant[s] that are .stripey:
var stripedOnes = hoop.querySelectorAll('.stripey')
This is like the CSS rule:
#hoop .stripey {
However, how do I do the same for child[ren], without using jQuery?
var stripedChildren = hoop.querySelectorAll('> .stripey')
Doesn't work, although in jQuery/Sizzle it does. What would be the JS equivalent of this CSS rule?
#hoop > .stripey {
Well, the most straightforward way would be to use the full selector inside querySelectorAll()
document.querySelectorAll("#hoop > .stripey");
But, if answering your specific question...
I believe the fanciest way to select an element's children based on a selector is:
turn the .children collection into an array
Filter each element testing it against a selector using .matches()
So:
var hoop = document.getElementById("hoop");
var stripedChildren = [].slice.call(hoop.children).filter(function(element) {
return element.matches(".stripey");
});
You can use following -
document.querySelectorAll("#hoop > .stripey");

Is there a way to get an element by its class name using JavaScript?

What is the best way to get an element by its class name using JavaScript?
Can I just use something like document.getElementByClassName('myClass') ?
Yup, there is such a thing as getElementsByClassName() and here's a browser support list which pretty much says "All recent browsers except IE8 and below"
var elements = document.getElementsByClassName('myClass');
also, there is querySelectorAll() which uses CSS selectors. It's pretty much similar to how jQuery does it. Here's a browser support list of it, which also says "All recent browsers except IE7 and below"
var elements = document.querySelectorAll('.myClass');
I prefer jQuery. Try it:
var elements = jQuery(".myClass");
This will collect all elements with class = "myClass". If you want iterate and do some thing with this elements:
jQuery(".myClass").each( function() {
// Getting element:
var element = jQuery(this);
doSomeStuff(element)
});

Categories