Extract a part of an id - javascript

I've got multiple divs with ids. I need to remove a certain part of a div ID and get it onto a variable. How can I do this? example:
<div id="fruitapple14754"></div>
<div id="fruitapple1564"></div>
<div id="fruitapple14"></div>
I need to remove fruitapple1 from the id and get the remaining part assigned to a variable. The length of fruitapple1 is always the same.

You can get an array of all the IDs like this:
var collection = [];
$('[id^="fruitapple"]').each(getId);
function getId() {
var id = $(this).attr('id').split('fruitapple1').pop();
collection.push(id);
}

You can use substr for this here is how to use:-
var ids=[];
$('[id^="fruitapple"]').each(function(){
var id=$(this).attr('id');
ids.push(id.substr(11));
});
alert(JSON.stringify(ids));
Demo

The simplest way would be to replace it with an empty string
$('[id^="fruitapple"]').each(function() {
var subId = $(this).attr('id').replace('fruitapple1', '');
console.log(subId);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="fruitapple14754"></div>
<div id="fruitapple1564"></div>
<div id="fruitapple14"></div>

You can use .substring() method of javascript.
Check out this fiddle.
Here is the snippet.
var divs = document.getElementsByTagName('div');
for (i = 0; i < divs.length; i++) {
var id = divs[i].id;
alert(id.substring(11)); // length of 'fruitapple1' = 11
}
<div id="fruitapple14754"></div>
<div id="fruitapple1564"></div>
<div id="fruitapple14"></div>

Try to use startwith selector,
$('[id^="fruitapple1"]').each(function() {
console.log(this.id.replace('fruitapple1', ''));
});
If you want to get it into an array variable then use map() like
console.log($('[id^="fruitapple1"]').map(function() {
return (this.id.replace('fruitapple1', ''));
}).get());
console.log($('[id^="fruitapple1"]').map(function() {
return (this.id.replace('fruitapple1', ''));
}).get());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fruitapple14754"></div>
<div id="fruitapple1564"></div>
<div id="fruitapple14"></div>

A simple answer using substring as suggested in my comment. I'm on mobile that's why it took long.
var idSubstring = document.getElementById("yourIdHere").id.substring(11);
alert(idSubstring);
Demo JSFiddle

Related

How i can get the fullclassname if i only know a part of it?

I need to get the classname from an element, but I only know a part of the name.
<div class="anotherclass my-class-no-1 onemoreclass...">div>
I can call the element with this
$([class*="my-class-no-"]...
But how can I get the complete classname?
Thanks a lot for explaining.
You can use className and search the class name containing your substring
let subclass = 'my-class-no-';
$('[class*="'+subclass+'"]').each(function() {
let name = this.className.split(' ').find((className) => {
return className.indexOf(subclass) !== -1;
});
console.log(name);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="anotherclass my-class-no-1 onemoreclass">
<div>
try it
console.log( $(".anotherclass").attr("class").split(' '));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="anotherclass my-class-no-1 onemoreclass"><div>
I'll do something like that:
(See comments in the snipper)
var search = "my-class-no-"; // Added to enter the searched class only once
var elms = $("[class*=" + search + "]"); // Get match
var classstr = elms.attr("class"); // Get the class attribute
// Split the string class attribute string to only keep the class that was searched
var myClass = classstr.substring(classstr.indexOf(search)).split(" ")[0];
console.log(myClass);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="anotherclass my-class-no-1 onemoreclass"></div>

replace set of strings in array

Using $('div#top_container').html(), I get the following as an example:
<div class="top" id="top_container">
<div class="example">First</div>
<div class="example">Second</div>
</div>
giving...
<div class="example">First</div>
<div class="example">Second</div>
Here, using .replace(), I want to replace <div class="example"> with *%^% (random set of characters) and remove </div>:
var content = $('div#top_container').html();
var clean_1 = content.replace('<div class="example">','*%^%'); //add $*!#$
var clean_2 = clean_1.replace('</div>',' '); //remove </div>
giving...
console.log(clean_2); --> *%^%First*%^%Second
Now, the number of example div elements can vary and I need to first find out how to target them all. Also is there a cleaner way to target both <div class="example"> and </div> at the same time?
EDIT:
I am not looking to change the html itself, but rather have the edited version as a variable that I can do stuff with (such as send it to php via ajax).
How would I do this?
Use replaceWith() method with a callback and generate prefered text string by getting text content using text() method.
$('div.example').replaceWith(function(v) {
return '%^%' + $(this).text();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="example">First</div>
<div class="example">Second</div>
</div>
UPDATE: If you don't want to update the original element then use clone() and do the remaining thinks on the cloned element.
var res = $('#parent')
// clone element
.clone()
// get element with `example` class
.find('.example')
// update content
.replaceWith(function(v) {
return '%^%' + $(this).text();
})
// back to previos selector and get html content
.end().html();
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div class="example">First</div>
<div class="example">Second</div>
</div>
Create one prototype like :
String.prototype.replaceAll = function (toReplace, replaceWith){
return this.split(toReplace).join(replaceWith);
}
and your jquery code be like :
$("div#top_container").each(function( i ) {debugger;
console.log(this.innerHTML.replaceAll('<div class="example">','*%^%').replaceAll('</div>',' ');)
});
You can use replaceWith function
$(function () {
$(".example").replaceWith(function(){
return "%^%"+$(this).text();
});
});
You can make a clone of container if you don't want to change original div.
var html="";
$(function () {
var newHtml = $("#top_container").clone();
$(newHtml).find(".example").replaceWith(function () {
html+= "%^%" + $(this).text();
});
});
console.log(html);

Get the id numbers (separatly) from the url and use it to select the id with that ID number (using jquery)

I am working on a website where I dont have any control on the code (functionality side. however even if I had the access I wouldn't be able to make any changes as I am a front end designer not a coder..lol). The only changes I can make is CSS, js.
What I am tring to do:
I got the url on the page like this:
www.test.com/#box1#box3#box5
(I am not sure if I can have more than one ID in a row. please advice. However thats how the developer has done it and I dont mind as there are no issues yet)
the page html
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<div id="box4"></div>
<div id="box5"></div>
I would like to take different ids from the URl and use it to hidhlight the divs with that ID (by addding a class name "highlight")
The result should be like this:
<div id="box1 highlight"></div>
<div id="box2"></div>
<div id="box3 highlight"></div>
<div id="box4"></div>
<div id="box5 highlight"></div>
I would like to learn the smart way of taking just the id numbers from the url and use it to select the div with that paticulat no.
just a quick explanation:
var GetID = (get the id from the URL)
$('#box' + GetID).addClass('highlight');
Try This...
var hashes =location.hash.split('#');
hashes.reverse().pop();
$.each(hashes , function (i, id) {
$('#'+id).addClass('highlight');
});
Working fiddle here
var ids = window.location.hash.split('#').join(',#').slice(1);
jQuery(ids).addClass('highlight');
or in plain JS:
var divs = document.querySelectorAll(ids);
[].forEach.call(divs, function(div) {
div.className = 'highlight';
});
There are various way to resolve this issue in JavaScript. Best is to use "split()" method and get an array of hash(es).
var substr = ['box1','box2']
// Plain JavaScript
for (var i = 0; i < substr.length; ++i) {
document.getElementById(substr[i]).className = "highlight"
}
//For Each
substr.forEach(function(item) {
$('#' + item).addClass('highlight')
});
//Generic loop:
for (var i = 0; i < substr.length; ++i) {
$('#' + substr[i]).addClass('highlight')
}
Fiddle - http://jsfiddle.net/ylokesh/vjk7wvxq/
Updated Fiddle with provided markup and added plain javascript solution as well -
http://jsfiddle.net/ylokesh/vjk7wvxq/1/
var x = location.hash;
var hashes = x.split('#');
for(var i=0; i< hashes.length; i++){
var GetID = hashes[i];
//with jQuery
$('#box' + GetID).addClass('highlight');
//with Javascript
document.getElementById('box' + GetID).className = document.getElementById('box' + GetID).className + ' highlight';
}

Count html elements in ajax returned data

I've got a jquery $.ajax call that returns a set of html from data.html which is like;
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
I'd like to count the amount of elements that have a class of .blah and i'm not sure how to do this.
I've tried:
data.html.getElementsByClassName('blah').length
but that obviously doesn't work!
Any suggestions gratefully received!!
Try utilizing .hasClass()
var data = {};
data.html = '<div class="blah item item-wrapper print"></div>'
+ '<div class="blah item item-wrapper digital"></div>';
var len = $.grep($.parseHTML(data.html), function(el, i) {
return $(el).hasClass("blah")
}).length;
$("body").html(len);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
You should be able to do this using either .filter() or .find(), depending on the exact format of your returned HTML. If the format is is exactly as you have stated, then the following should work:
$.get("data.html", function(data) {
var length = $(data).filter(".blah").length;
});
If there is some sort of wrapper element around your items with class blah, then you would use .find():
$.get("data.html", function(data) {
var length = $(data).find(".blah").length;
});
$('.blah','context').length
Replace context by object in which you want to search

Trying to convert the values in a node to an array, clone a specific element and append the array items to that node with a class

<body>
<section id="que-container">
<div class="num" style="display: none">1000</div>
<section id="numberContainer">
<span class="number"></span>
</section>
<br class="clear">
</section>
<script src="components/jquery/jquery.min.js"></script>
<script src="components/bootstrap/js/bootstrap-button.js"></script>
<script src="components/bootstrap/js/bootstrap-carousel.js"></script>
<script src="js/scripts.js"></script>
<script>
$(document).ready(function(){
var numbers = $('.number');
var num = $(".num").html();
var arr = num.split('');
for (var i = 1; i < arr.length ; i++) {
$('#numberContainer').append(numbers.clone());
$('.number').append(arr[i]);
}
$('.number').each(function(i, val) {
$(this).addClass('numStyle');
})
});
</script>
</body>
I am trying to get the values inside the '.num' div, convert it to an array and append the array's items to the '#numberContainer' within spans with the 'number' class. i am not getting any errors on the console but the code doesnt seem to work. any help? thanks
Your code has to be like this because arrays are 0 index based:
fiddle: http://jsfiddle.net/DZJ6p/
var numbers = $('.number');
var num = $(".num").html();
var arr = num.split('');
for (var i = 0; i < arr.length; i++) {
$('#numberContainer').append(numbers.clone().append(arr[i]));
}
$('.number').each(function(i, val) {
$(this).addClass('numStyle');
});
you have a wrong selector here
$('.numbers').append(arr[i]); // i didn't find any element with numbers class
it should be
$('.number').append(arr[i]);
OR
numbers.append(arr[i]);
UPDATED
your for loop starts with var i as 1... so it is missing the first index of arr i.e. arr[0], I used this in youe code..
$('#numberContainer').append(numbers.clone().append(arr[i])); // u can use text(arr[i])) here
here is the fiddle...
http://jsfiddle.net/zLHxV/
i am not sure why you are using $('#numberContainer').append(numbers.clone());. Can you take a look at the js fiddle where i have put your code there.

Categories