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);
Related
So, I'm trying to only show certain part of the text. The info is passed like this. Ex: ["PS4"] and I only want the PS4 text to show so I did this with jQuery:
var text = $('.gender').text();
var text2=text.substring(text.indexOf('"')+1,text.lastIndexOf('"'));
$('.gender').text(text2);
The problem is that I want to change every single element text that have .gender class but only having their corresponding text, like so:
["PS4"]["XBOX"]
<div class="gender">PS4</div><div class="gender">XBOX</div>
I tried to do it with .each() function but I got something like this:
<div class="gender">PS4"]["XBOX</div><div class="gender">PS4"]["XBOX</div>
Here's the code with jQuery .each():
$('.gender').each(function(){
var text = $('.gender').text();
var text2=text.substring(text.indexOf('"')+1,text.lastIndexOf('"'));
$('.gender').text(text2);
});
EDIT:
I have an HTML with this:
<div class="gender">["PS4"]</div>
<div class="gender">["XBOX"]</div>
So I want to remove the '[""]' from every element that have .gender class so it shows like this:
<div class="gender">PS4</div>
<div class="gender">XBOX</div>
Use $(this) and not $(".gender")
$('.gender').each(function() {
var text = $(this).text();
var text2 = text.substring(text.indexOf('"') + 1, text.lastIndexOf('"'));
$(this).text(text2);
});
demo
$('.gender').each(function() {
var text = $(this).text();
var text2 = text.substring(text.indexOf('"') + 1, text.lastIndexOf('"'));
$(this).text(text2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gender">["PS4"]</div>
<div class="gender">["XBOX"]</div>
You may go for RegEx, with $.text(callback)
$(function() {
$('.gender').text(function() {
return $(this).text().replace(/^\[\"(.*)\"\]$/, '$1');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gender">["PS4"]</div>
<div class="gender">["XBOX"]</div>
Breakup of, ^\[\"(.*)\"\]$ as below:
^ starts with
(.*) group having any match of any length
$ ends with
Try this one also:
$('.gender').each(function() {
var text = $(this).text();
var text2 = text.replace("\"]", "");
text2 = text2.replace("[\"", "");
$(this).text(text2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gender">["PS4"]</div>
<div class="gender">["XBOX"]</div>
ho,
I have a div that I access like so:
var gridcellrowvalue0 = gridcell0.innerHTML;
This returns to me the following div:
<div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>
In my JS I would like to accesss the "DefaultText" variable and I have tried this:
gridcellrowvalue0.innerHTML;
gridcellrowvalue0.getAttribute("data-originaltext");
But none of them work. I'm assuming that getAttribute doesn't work because it is not really an element, it's innerhtml.
My goal is to use the "DefaultText" value in an IF-statement and therefore I simply need it.
I appreciate any pointers, my friends!
You could access your element directly from gridcell0 using gridcell0.querySelector('.DivOverflowNoWrap') instead, like :
var gridcell0 = document.querySelector('#x');
console.log( gridcell0.querySelector('.DivOverflowNoWrap').innerHTML );
Snippet:
var gridcell0 = document.querySelector('#x');
if (gridcell0.querySelector('.DivOverflowNoWrap') !== null) {
console.log(gridcell0.querySelector('.DivOverflowNoWrap').innerHTML);
} else {
console.log('Does not exist');
}
<div id="x">
<div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>
</div>
With Javascript also it can be achieved but I am showing here using jQuery
$('document').ready(function() {
var div = $(".DivOverflowNoWrap");
var text = div.text();
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>
The problem is how you access the div in the first place. If you do it like you described (with gridcell0.innerHTML). It will return a string. Not an HTML element.
Therefore you can't use .getAttribute or .innerHTML, because you try to apply it on a string. Access your div differently (querySelector or getElementBy...) and you will be able to use those.
You can use jquery:
$("[class='DivOverflowNoWrap']").text();
$("[class='DivOverflowNoWrap']").attr("data-originaltext")
It's pretty simple:
<html><head></head>
<div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>
<script>
test();
function test(){
var x=document.getElementsByClassName("DivOverflowNoWrap Ellipsis")[0].getAttribute("data-originaltext");
alert(x);
}
</script>
</html>
in DOM I already have a wrapper
<div id="wrapper"></div>
which I need to fill with bunch of divs, where each will represent new category.
Each category will be then filled with various cards representing items of that category. Like this:
<div id="wrapper">
<div data-category="puppy">
Dynamically created category wrapper
<div class="puppy1">...</div>
<div class="puppy2">...</div>
</div>
<div data-category="cat">
...
</div>
</div>
I use following code to create and fill category, but I always end up either having empty category or having a string inside reprenting the html.
var categoryWrapper = document.createElement("div");
categoryWrapper.setAttribute("data-category", key);
categoryWrapper.innerHtml = htmlString;
Here is a fiddle demo of my issue.
https://jsfiddle.net/uuqj4ad5/
I'll be grateful for a help.
There is a typo, innerHml should be innerHTML(Javascript object properties are case sensitive) otherwise it simply add an additional property and nothing gets happened.
categoryWrapper.innerHTML = htmlString;
var htmlString = "<div class='card'><div class='cardImg'><img src='http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg' alt='Puppy'></div><div class='cardContent'><div class='cardInfo'><p>Puppy Yawning</p></div><div class='cardDesc'><p>Awww!</p></div></div></div>";
var outerWrapper = $("#wrapper");
var categoryWrapper = document.createElement("div");
categoryWrapper.innerHTML = htmlString;
outerWrapper.append(categoryWrapper);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>
Under this title various categories should be dynamically created
</h3>
<div id="wrapper">outerWrapper waiting for dynamic data...</div>
</div>
FYI : If you want to remove the existing content then use html() method instead of append() method.
innerHtml
should be
innerHTML
Javascript is case sensitive
If you are using jQuery why do you want to mix jQuery and Vanilla JS.
var outerWrapper = $("#wrapper");
// I created new categoryWrapper object
var categoryWrapper = $('<div/>', {
html: htmlString
});
debugger;
// WHen I have the category filled with inner data, I will append it into outerwrapper
outerWrapper.append(categoryWrapper);
jsFiddle
Checkout my fiddle:-
https://jsfiddle.net/dhruv1992/1xg18a3f/1/
your js code should look like this
// This is dynamically filled html template. The data comes from some JSON.
var htmlString = "<div class='card'><div class='cardImg'><img src='http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg' alt='Puppy'></div><div class='cardContent'><div class='cardInfo'><p>Puppy Yawning</p></div><div class='cardDesc'><p>Awww!</p></div></div></div>";
// This outer wrapper will in the end contain few categories
var outerWrapper = $("#wrapper");
outerWrapper.append('<div>'+htmlString+'</div>')
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
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