Grab the class from an element JS - javascript

I have an li tag that looks like:
<li class="active_fix generator" data-selected="1"></li>
Within my onClick event I have a console.log on $(this) and I get back
[li.active_fix generator] - among a few things in my console window.
How can I grab the class. So for example save the classname active_fix as a var but not the second class name generator.
$('active_fix').on('click', function() {
console.log($(this));
})
Thanks.

You can split the class name,
$(this).attr("class").split(" ")[0]
We are getting the class name using attr and splitting the string by a space, then we are getting the first key in the array.
Reading Material
attr
split

Try to use .attr("attributeName") to get its attribute(any),
$('.active_fix').on('click', function() {
console.log($(this).attr("class").split(" ")[0]); //Jquery
console.log(this.className.split(" ")[0]); //Pure Javascript
});
this.className will return a string "active_fix generator". Basically multiple classes to an element can be applied by adding a space as a delimiter. So you can split that returned string with space to get array of class names. And from that array [0] will get you the first class.

You can use classList to retrieve a list of the elemnent classes:
$('.active_fix').on('click', function() {
alert(this.classList[0]);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="active_fix generator" data-selected="1">...</li>

$('.active_fix').on('click', function() {
alert($(this).attr("class").split(" ")[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="active_fix generator" data-selected="1"></li>

DevJunior Try This , It will help you
$('.active_fix').on('click', function() {
console.log($('.active_fix').attr('class').split(' ')[0]);
});

$('.active_fix').on('click', function() {
alert(this.classList[0]);
})

Related

how to find string with number selector in jquery

I want to know how to find the class along with number digits, for instance, the class maybe like this: .test_ico1, .test_ico2, .test_ico3, .test_ico4.
Jquery
$('.test_ico' + '/[0-9]/').each(function(){
var a = window.getComputedStyle(this,':after').content;
$(this).parent().hover(function(){
$(this).attr('data-content', a);
});
});
You can use ^(starts with) symbol.
Also it's called Attribute Starts With Selector
$('[class^="test_ico"]').each(function(){
Short example:
$('[class^="myClass"]').each(function(){
$(this).addClass('active');
});
.active{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="myClass1">1</li>
<li class="myClass2">2</li>
<li class="Class3">3</li>
</ul>
Try attribute contains selector [attribute*=value]
$('[class*="test_ico"]').each(function(){
var a = window.getComputedStyle(this,':after').content;
$(this).parent().hover(function(){
$(this).attr('data-content', a);
});
});
Note: Prefer this over #Alexandru's answer only if your element has multiple classes.
You can use the starts with attribute selector, no need for a each function, you need the hover event over the test_ico not the parent
$('[class^="test_ico"]').hover(function() {
var a = window.getComputedStyle(this,':after').content;
$(this).parent().attr('data-content', a);
});

Hide an element when a specific string is present in the url

I want to hide a button when the string "wholesale' is present in the url. I've tried a few variations of the following code but it just won't work.
<script type="text/javascript">
$(document).ready(function () {
if (/wholesale/.test(window.location.href)) {
document.getElementsByClassName('variations_button')[0].style.display = 'none';
}
});
</script>
May be this will help.
var patt = new RegExp("wholesale");
if (patt.test(window.location.href)) {
$('.variations_button').hide();
}
you are doing wrong with the select element by class name code
it should be like this:
document.getElementsByClassName('variations_button')[0].style.display='none'
Note:
document.getElementsByClassName returns an array of elements with the same class name. So document.getElementsByClassName('variations_button')[0] will return the first element with the class name variations_button.
you have a problem with getElementByClassName, it should be getElementsByClassName and will return a HTMLCollection (Array like object) not an element. You should probably also use jQuery if that is already loaded on the page. jQuery is an array like object of HTMLElements that will give you methods that will run over the entire collection.
edit:
here is a working example, click 'Run code snippet' to see the result. I had to change the regex to match what was in the snippet, but you should get the idea.
console.log( 'is jQuery installed on the page', typeof $ !== void 0 );
$(function () {
console.log( 'href', window.location.href );
if (/stacksnippets/.test(window.location.href)) {
console.log('regex found in href');
$('.variations_button').css('background', '#3cf');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
<button class="variations_button">variations button</button>

Why does jQuery, outputs same rel each time?

so basically here is my script:
http://jsfiddle.net/JJFap/42/
Code -
jQuery(document).ready(function() {
var rel = new Array();
var count = 0;
jQuery(".setting").each(function() {
rel[count] = [];
if(jQuery("span").attr("rel")) {
rel[count].push(jQuery("span").attr("rel"));
}
console.log(count);
count++;
});
jQuery("body").text(rel);
console.log(rel);
});​
and
<div class="setting">
<span rel="Variable">Variable</span>
<span rel="Item">Item</span>
<span rel="Something">Something</span>
</div>
<div>
<span rel="Smth">Smth</span>
<span>Sec</span>
</div>
<div class="setting">
<span>Second</span>
<span rel="first">First</span>
<span rel="Third">Third</span>
</div>
​my question, is why does it display Variable, variable?
I would like it to display Variable, First, but I'm not able to do.
Basically what I would like to achieve is create new array, in which insert each div.setting span elements with rel attribute array.
So basically in this example it should output -
Array (
Array[0] => "Variable","Item","Something";
Array[1] => "first","Third";
)
Hope you understood what I meant :)
EDIT:
In my other example I tried to add jQuery("span").each(function() ... inside first each function, but it outputted two full arrays of all span elements with rel. I can't have different classes / ids for each div element, since all will have same class.
jQuery('span') is going to find ALL spans in your page, and then pull out the rel attribute of the first one. Since you don't provide a context for that span search, you'll always get the same #1 span in the document.
You should be using this:
jQuery('span',this).each(function() {
rel[count] = [];
if (jQuery(this).attr("rel")) {
rel[count].push(jQuery(this).attr("rel"));
}
console.log(count);
count++;
})
instead of this:
rel[count] = [];
if(jQuery("span").attr("rel")) {
rel[count].push(jQuery("span").attr("rel"));
}
console.log(count);
count++;
http://jsfiddle.net/mblase75/JJFap/52/
The trick is to use a second .each to loop over all the span tags inside each <div class="setting"> -- your original code was using jQuery("span"), which would just grab the first span tag in the document every time.
In addition to what has been said, you can also get rid of the count and one push() when using jQuery.fn.map() as well as getting rid of the if when adding [rel] to the selector:
jQuery(document).ready(function() {
var rel = [];
jQuery(".setting").each(function() {
rel.push(jQuery(this).find('span[rel]').map(function() {
return this.getAttribute('rel');
}).get());
});
jQuery("body").text(rel);
console.log(rel);
});
Within the .each() method, you have this code a couple times: jQuery("span").attr("rel"). That code simply looks for ALL span tags on the page. When you stick it inside the .push() method, it's just going to push the value for the rel attribute of the first jQuery object in the collection. Instead, you want to do something like $(this).find('span'). This will cause it to look for any span tags that are descendants of the current .setting element that the .each() method is iterating over.

How to change text inside span with jQuery, leaving other span contained nodes intact?

I have the following HTML snippet:
<span class="target">Change me <a class="changeme" href="#">now</a></span>
I'd like to change the text node (i.e. "Change me ") inside the span from jQuery, while leaving the nested <a> tag with all attributes etc. intact. My initial huch was to use .text(...) on the span node, but as it turns out this will replace the whole inner part with the passed textual content.
I solved this with first cloning the <a> tag, then setting the new text content of <span> (which will remove the original <a> tag), and finally appending the cloned <a> tag to my <span>. This works, but feels such an overkill for a simple task like this. Btw. I can't guarantee that there will be an initial text node inside the span - it might be empty, just like:
<span class="target"><a class="changeme" href="#">now</a></span>
I did a jsfiddle too. So, what would be the neat way to do this?
Try something like:
$('a.changeme').on('click', function() {
$(this).closest('.target').contents().not(this).eq(0).replaceWith('Do it again ');
});
demo: http://jsfiddle.net/eEMGz/
ref: http://api.jquery.com/contents/
Update:
I guess I read your question wrong, and you're trying to replace the text if it's already there and inject it otherwise. For this, try:
$('a.changeme').on('click', function() {
var
$tmp = $(this).closest('.target').contents().not(this).eq(0),
dia = document.createTextNode('Do it again ');
$tmp.length > 0 ? $tmp.replaceWith(dia) : $(dia).insertBefore(this);
});
​Demo: http://jsfiddle.net/eEMGz/3/
You can use .contents():
//set the new text to replace the old text
var newText = 'New Text';
//bind `click` event handler to the `.changeme` elements
$('.changeme').on('click', function () {
//iterate over the nodes in this `<span>` element
$.each($(this).parent().contents(), function () {
//if the type of this node is undefined then it's a text node and we want to replace it
if (typeof this.tagName == 'undefined') {
//to replace the node we can use `.replaceWith()`
$(this).replaceWith(newText);
}
});
});​
Here is a demo: http://jsfiddle.net/jasper/PURHA/1/
Some docs for ya:
.contents(): http://api.jquery.com/contents
.replaceWith(): http://api.jquery.com/replacewith
typeof: https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof
Update
var newText = 'New Text';
$('a').on('click', function () {
$.each($(this).parent().contents(), function () {
if (typeof this.tagName == 'undefined') {
//instead of replacing this node with the replacement string, just replace it with a blank string
$(this).replaceWith('');
}
});
//then add the replacement string to the `<span>` element regardless of it's initial state
$(this).parent().prepend(newText);
});​
Demo: http://jsfiddle.net/jasper/PURHA/2/
You can try this.
var $textNode, $parent;
$('.changeme').on('click', function(){
$parent = $(this).parent();
$textNode= $parent.contents().filter(function() {
return this.nodeType == 3;
});
if($textNode.length){
$textNode.replaceWith('Content changed')
}
else{
$parent.prepend('New content');
}
});
Working demo - http://jsfiddle.net/ShankarSangoli/yx5Ju/8/
You step out of jQuery because it doesn't help you to deal with text nodes. The following will remove the first child of every <span> element with class "target" if and only if it exists and is a text node.
Demo: http://jsfiddle.net/yx5Ju/11/
Code:
$('span.target').each(function() {
var firstChild = this.firstChild;
if (firstChild && firstChild.nodeType == 3) {
firstChild.data = "Do it again";
}
});
This is not a perfect example I guess, but you could use contents function.
console.log($("span.target").contents()[0].data);
You could wrap the text into a span ... but ...
try this.
http://jsfiddle.net/Y8tMk/
$(function(){
var txt = '';
$('.target').contents().each(function(){
if(this.nodeType==3){
this.textContent = 'done ';
}
});
});
You can change the native (non-jquery) data property of the object. Updated jsfiddle here: http://jsfiddle.net/elgreg/yx5Ju/2/
Something like:
$('a.changeme3').click(function(){
$('span.target3').contents().get(0).data = 'Do it again';
});
The contents() gets the innards and the get(0) gets us back to the original element and the .data is now a reference to the native js textnode. (I haven't tested this cross browser.)
This jsfiddle and answer are really just an expanded explanation of the answer to this question:
Change text-nodes text
$('a.changeme').click(function() {
var firstNode= $(this).parent().contents()[0];
if( firstNode.nodeType==3){
firstNode.nodeValue='New text';
}
})
EDIT: not sure what layout rules you need, update to test only first node, otherwise adapt as needed

Add Different Style to list tag using jquery/javascript

Is there any ways to add different style class to all li in a ul tag using jquery/javascript/php.
Consider I have a list as follows
<ul><li>a</li><li>b</li><li>c</li><li>d</li><li>e</li></ul>
I would like to add as follows
<ul><li class='cat1'>a</li><li class='cat2'>b</li><li class='cat3'>c</li><li class='cat4'>d</li><li class='cat5'>e</li></ul>
As simple as:
$('ul').children('li').addClass(function (i) {
return 'cat' + (i+1);
});
http://api.jquery.com/addClass/
If you want to set the class, the cheaper way to do it is by using .attr() and the index in its setter function, like this:
$("ul li").attr("class", function(i) {
return "cat" + (i+1);
});
If you aren't setting it and just adding, use .addClass(function(i) instead of .attr("class", function(i).
$('ul').children('li').each(function(i,v){
$(this).addClass('cat'+(i+1));
});

Categories